langchain-6-streaming-responses
БесплатноБез исполняемых скриптовНе проверенSub-skill of langchain: 6. Streaming Responses.
от vamseeachanta★ 21 звезда на GitHubОб этом скилле
6. Streaming Responses
6. Streaming Responses
Streaming Chain:
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
import asyncio
def create_streaming_chain():
"""Create chain that supports streaming output."""
llm = ChatOpenAI(
model="gpt-4",
temperature=0.7,
streaming=True
)
prompt = ChatPromptTemplate.from_template(
"You are an expert engineer. Explain in detail: {topic}"
)
chain = prompt | llm | StrOutputParser()
return chain
# Synchronous streaming
def stream_response(chain, topic: str):
"""Stream response token by token."""
print("Response: ", end="", flush=True)
for chunk in chain.stream({"topic": topic}):
print(chunk, end="", flush=True)
print("\n")
# Async streaming
async def astream_response(chain, topic: str):
"""Async stream response."""
print("Response: ", end="", flush=True)
async for chunk in chain.astream({"topic": topic}):
print(chunk, end="", flush=True)
print("\n")
# Usage
chain = create_streaming_chain()
# Sync streaming
stream_response(chain, "mooring line catenary equations")
# Async streaming
asyncio.run(astream_response(chain, "wave-structure interaction"))
Streaming with Callbacks:
from langchain_openai import ChatOpenAI
from langchain_core.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
from langchain_core.callbacks.base import BaseCallbackHandler
from typing import Any, Dict, List
import json
class CustomStreamHandler(BaseCallbackHandler):
"""Custom callback handler for streaming."""
def __init__(self):
self.tokens = []
self.final_response = ""
def on_llm_new_token(self, token: str, **kwargs) -> None:
"""Called when a new token is generated."""
self.tokens.append(token)
self.final_response += token
# Could send to WebSocket, write to file, etc.
print(token, end="", flush=True)
def on_llm_end(self, response: Any, **kwargs) -> None:
"""Called when LLM finishes."""
print(f"\n\n[Generation complete: {len(self.tokens)} tokens]")
def on_llm_error(self, error: Exception, **kwargs) -> None:
"""Called on error."""
print(f"\n[Error: {error}]")
def stream_with_callbacks(prompt: str):
"""Stream with custom callbacks."""
handler = CustomStreamHandler()
llm = ChatOpenAI(
model="gpt-4",
temperature=0.7,
streaming=True,
callbacks=[handler]
)
response = llm.invoke(prompt)
return handler.final_response, handler.tokens
# Usage
response, tokens = stream_with_callbacks(
"Explain the design considerations for a turret mooring system"
)
print(f"\nTotal tokens: {len(tokens)}")
Установить langchain-6-streaming-responses в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл langchain-6-streaming-responses?
Sub-skill of langchain: 6. Streaming Responses.
Как установить скилл langchain-6-streaming-responses?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл langchain-6-streaming-responses запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic