from langgraph_sdk import get_clientclient = get_client(url=<DEPLOYMENT_URL>, api_key=<API_KEY>)# Using the graph deployed with the name "agent"assistant_id = "agent"# create a threadthread = await client.threads.create()thread_id = thread["thread_id"]# create a streaming runasync for chunk in client.runs.stream( thread_id, assistant_id, input=inputs, stream_mode="updates"): print(chunk.data)
Copy
import { Client } from "@langchain/langgraph-sdk";const client = new Client({ apiUrl: <DEPLOYMENT_URL>, apiKey: <API_KEY> });// Using the graph deployed with the name "agent"const assistantID = "agent";// create a threadconst thread = await client.threads.create();const threadID = thread["thread_id"];// create a streaming runconst streamResponse = client.runs.stream( threadID, assistantID, { input, streamMode: "updates" });for await (const chunk of streamResponse) { console.log(chunk.data);}
스레드를 생성합니다:
Copy
curl --request POST \--url <DEPLOYMENT_URL>/threads \--header 'Content-Type: application/json' \--data '{}'
실행 중인 LangGraph API 서버가 있으면, LangGraph SDK를 사용하여 상호작용할 수 있습니다.
Python
JavaScript
cURL
Copy
from langgraph_sdk import get_clientclient = get_client(url=<DEPLOYMENT_URL>)# Using the graph deployed with the name "agent"assistant_id = "agent"# create a threadthread = await client.threads.create()thread_id = thread["thread_id"]# create a streaming runasync for chunk in client.runs.stream( # (1)! thread_id, assistant_id, input={"topic": "ice cream"}, stream_mode="updates" # (2)!): print(chunk.data)
client.runs.stream() 메서드는 스트리밍 출력을 생성하는 이터레이터를 반환합니다.
2. stream_mode="updates"를 설정하면 각 노드 실행 후 그래프 상태의 업데이트만 스트리밍합니다. 다른 스트림 모드도 사용할 수 있습니다. 자세한 내용은 지원되는 스트림 모드를 참조하세요.
Copy
import { Client } from "@langchain/langgraph-sdk";const client = new Client({ apiUrl: <DEPLOYMENT_URL> });// Using the graph deployed with the name "agent"const assistantID = "agent";// create a threadconst thread = await client.threads.create();const threadID = thread["thread_id"];// create a streaming runconst streamResponse = client.runs.stream( // (1)! threadID, assistantID, { input: { topic: "ice cream" }, streamMode: "updates" // (2)! });for await (const chunk of streamResponse) { console.log(chunk.data);}
client.runs.stream() 메서드는 스트리밍 출력을 생성하는 이터레이터를 반환합니다.
streamMode: "updates"를 설정하면 각 노드 실행 후 그래프 상태의 업데이트만 스트리밍합니다. 다른 스트림 모드도 사용할 수 있습니다. 자세한 내용은 지원되는 스트림 모드를 참조하세요.
스레드를 생성합니다:
Copy
curl --request POST \--url <DEPLOYMENT_URL>/threads \--header 'Content-Type: application/json' \--data '{}'
{'run_id': '1f02c2b3-3cef-68de-b720-eec2a4a8e920', 'attempt': 1}{'refine_topic': {'topic': 'ice cream and cats'}}{'generate_joke': {'joke': 'This is a joke about ice cream and cats'}}
스트림 모드 updates와 values를 사용하여 그래프가 실행될 때 상태를 스트리밍합니다.
updates는 그래프의 각 단계 후 상태의 업데이트를 스트리밍합니다.
values는 그래프의 각 단계 후 상태의 전체 값을 스트리밍합니다.
예제 그래프
Copy
from typing import TypedDictfrom langgraph.graph import StateGraph, START, ENDclass State(TypedDict): topic: str joke: strdef refine_topic(state: State): return {"topic": state["topic"] + " and cats"}def generate_joke(state: State): return {"joke": f"This is a joke about {state['topic']}"}graph = ( StateGraph(State) .add_node(refine_topic) .add_node(generate_joke) .add_edge(START, "refine_topic") .add_edge("refine_topic", "generate_joke") .add_edge("generate_joke", END) .compile())
상태 유지 실행
아래 예제는 스트리밍 실행의 출력을 유지하려는 경우를 가정하며, 체크포인터 DB에 저장하고 스레드를 생성합니다. 스레드를 생성하려면:
Python
JavaScript
cURL
Copy
from langgraph_sdk import get_clientclient = get_client(url=<DEPLOYMENT_URL>)# Using the graph deployed with the name "agent"assistant_id = "agent"# create a threadthread = await client.threads.create()thread_id = thread["thread_id"]
Copy
import { Client } from "@langchain/langgraph-sdk";const client = new Client({ apiUrl: <DEPLOYMENT_URL> });// Using the graph deployed with the name "agent"const assistantID = "agent";// create a threadconst thread = await client.threads.create();const threadID = thread["thread_id"]
Copy
curl --request POST \--url <DEPLOYMENT_URL>/threads \--header 'Content-Type: application/json' \--data '{}'
실행 출력을 유지할 필요가 없는 경우, 스트리밍할 때 thread_id 대신 None을 전달할 수 있습니다.
스트리밍 출력에 서브그래프의 출력을 포함하려면, 상위 그래프의 .stream() 메서드에서 subgraphs=True를 설정할 수 있습니다. 이렇게 하면 상위 그래프와 모든 서브그래프의 출력을 스트리밍합니다.
Copy
async for chunk in client.runs.stream( thread_id, assistant_id, input={"foo": "foo"}, stream_subgraphs=True, # (1)! stream_mode="updates",): print(chunk)
서브그래프의 출력을 스트리밍하려면 stream_subgraphs=True를 설정합니다.
확장된 예제: 서브그래프에서 스트리밍
다음은 LangGraph API 서버에서 실행할 수 있는 예제 그래프입니다.
자세한 내용은 LangSmith 빠른 시작을 참조하세요.
Copy
# graph.pyfrom langgraph.graph import START, StateGraphfrom typing import TypedDict# Define subgraphclass SubgraphState(TypedDict): foo: str # note that this key is shared with the parent graph state bar: strdef subgraph_node_1(state: SubgraphState): return {"bar": "bar"}def subgraph_node_2(state: SubgraphState): return {"foo": state["foo"] + state["bar"]}subgraph_builder = StateGraph(SubgraphState)subgraph_builder.add_node(subgraph_node_1)subgraph_builder.add_node(subgraph_node_2)subgraph_builder.add_edge(START, "subgraph_node_1")subgraph_builder.add_edge("subgraph_node_1", "subgraph_node_2")subgraph = subgraph_builder.compile()# Define parent graphclass ParentState(TypedDict): foo: strdef node_1(state: ParentState): return {"foo": "hi! " + state["foo"]}builder = StateGraph(ParentState)builder.add_node("node_1", node_1)builder.add_node("node_2", subgraph)builder.add_edge(START, "node_1")builder.add_edge("node_1", "node_2")graph = builder.compile()
실행 중인 LangGraph API 서버가 있으면, LangGraph SDK를 사용하여 상호작용할 수 있습니다.
Python
JavaScript
cURL
Copy
from langgraph_sdk import get_clientclient = get_client(url=<DEPLOYMENT_URL>)# Using the graph deployed with the name "agent"assistant_id = "agent"# create a threadthread = await client.threads.create()thread_id = thread["thread_id"]async for chunk in client.runs.stream( thread_id, assistant_id, input={"foo": "foo"}, stream_subgraphs=True, # (1)! stream_mode="updates",): print(chunk)
서브그래프의 출력을 스트리밍하려면 stream_subgraphs=True를 설정합니다.
Copy
import { Client } from "@langchain/langgraph-sdk";const client = new Client({ apiUrl: <DEPLOYMENT_URL> });// Using the graph deployed with the name "agent"const assistantID = "agent";// create a threadconst thread = await client.threads.create();const threadID = thread["thread_id"];// create a streaming runconst streamResponse = client.runs.stream( threadID, assistantID, { input: { foo: "foo" }, streamSubgraphs: true, // (1)! streamMode: "updates" });for await (const chunk of streamResponse) { console.log(chunk);}
서브그래프의 출력을 스트리밍하려면 streamSubgraphs: true를 설정합니다.
스레드를 생성합니다:
Copy
curl --request POST \--url <DEPLOYMENT_URL>/threads \--header 'Content-Type: application/json' \--data '{}'
messages-tuple 스트리밍 모드를 사용하여 노드, 도구, 서브그래프 또는 태스크를 포함한 그래프의 모든 부분에서 대규모 언어 모델(LLM) 출력을 토큰 단위로 스트리밍합니다.messages-tuple 모드에서 스트리밍된 출력은 (message_chunk, metadata) 튜플입니다:
message_chunk: LLM의 토큰 또는 메시지 세그먼트입니다.
metadata: 그래프 노드 및 LLM 호출에 대한 세부 정보를 포함하는 딕셔너리입니다.
예제 그래프
Copy
from dataclasses import dataclassfrom langchain.chat_models import init_chat_modelfrom langgraph.graph import StateGraph, START@dataclassclass MyState: topic: str joke: str = ""model = init_chat_model(model="openai:gpt-4o-mini")def call_model(state: MyState): """Call the LLM to generate a joke about a topic""" model_response = model.invoke( # (1)! [ {"role": "user", "content": f"Generate a joke about {state.topic}"} ] ) return {"joke": model_response.content}graph = ( StateGraph(MyState) .add_node(call_model) .add_edge(START, "call_model") .compile())
LLM이 stream이 아닌 invoke를 사용하여 실행되는 경우에도 메시지 이벤트가 발생한다는 점에 유의하세요.
Python
JavaScript
cURL
Copy
async for chunk in client.runs.stream( thread_id, assistant_id, input={"topic": "ice cream"}, stream_mode="messages-tuple",): if chunk.event != "messages": continue message_chunk, metadata = chunk.data # (1)! if message_chunk["content"]: print(message_chunk["content"], end="|", flush=True)
“messages-tuple” 스트림 모드는 (message_chunk, metadata) 튜플의 이터레이터를 반환합니다. 여기서 message_chunk는 LLM이 스트리밍한 토큰이고 metadata는 LLM이 호출된 그래프 노드와 기타 정보에 대한 정보가 포함된 딕셔너리입니다.
“messages-tuple” 스트림 모드는 (message_chunk, metadata) 튜플의 이터레이터를 반환합니다. 여기서 message_chunk는 LLM이 스트리밍한 토큰이고 metadata는 LLM이 호출된 그래프 노드와 기타 정보에 대한 정보가 포함된 딕셔너리입니다.