mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-09-30 13:35:09 +02:00
176 KiB
176 KiB
In [ ]:
! pip install langchain_community tiktoken langchain-openai langchainhub chromadb langchain langgraphIn [14]:
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import WebBaseLoader
from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings
urls = [
"https://lilianweng.github.io/posts/2023-06-23-agent/",
"https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/",
"https://lilianweng.github.io/posts/2023-10-25-adv-attack-llm/",
]
docs = [WebBaseLoader(url).load() for url in urls]
docs_list = [item for sublist in docs for item in sublist]
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
chunk_size=100, chunk_overlap=50
)
doc_splits = text_splitter.split_documents(docs_list)
# Add to vectorDB
vectorstore = Chroma.from_documents(
documents=doc_splits,
collection_name="rag-chroma",
embedding=OpenAIEmbeddings(),
)
retriever = vectorstore.as_retriever()In [17]:
from langchain.tools.retriever import create_retriever_tool
tool = create_retriever_tool(
retriever,
"retrieve_blog_posts",
"Search and return information about Lilian Weng blog posts on LLM agents, prompt engineering, and adversarial attacks on LLMs.",
)
tools = [tool]
from langgraph.prebuilt import ToolExecutor
tool_executor = ToolExecutor(tools)In [18]:
import operator
from typing import Annotated, Sequence, TypedDict
from langchain_core.messages import BaseMessage
class AgentState(TypedDict):
messages: Annotated[Sequence[BaseMessage], operator.add]In [19]:
import json
import operator
from typing import Annotated, Sequence, TypedDict
from langchain.output_parsers import PydanticOutputParser
from langchain.prompts import PromptTemplate
from langchain.tools.render import format_tool_to_openai_function
from langchain_core.messages import BaseMessage, FunctionMessage
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import ToolInvocation
### Edges
def should_retrieve(state):
"""
Decides whether the agent should retrieve more information or end the process.
This function checks the last message in the state for a function call. If a function call is
present, the process continues to retrieve information. Otherwise, it ends the process.
Args:
state (messages): The current state of the agent, including all messages.
Returns:
str: A decision to either "continue" the retrieval process or "end" it.
"""
print("---DECIDE TO RETRIEVE---")
messages = state["messages"]
last_message = messages[-1]
# If there is no function call, then we finish
if "function_call" not in last_message.additional_kwargs:
print("---DECISION: DO NOT RETRIEVE / DONE---")
return "end"
# Otherwise there is a function call, so we continue
else:
print("---DECISION: RETRIEVE---")
return "continue"
def check_relevance(state):
"""
Determines whether the Agent should continue based on the relevance of retrieved documents.
This function checks if the last message in the conversation is of type FunctionMessage, indicating
that document retrieval has been performed. It then evaluates the relevance of these documents to the user's
initial question using a predefined model and output parser. If the documents are relevant, the conversation
is considered complete. Otherwise, the retrieval process is continued.
Args:
state messages: The current state of the conversation, including all messages.
Returns:
str: A directive to either "end" the conversation if relevant documents are found, or "continue" the retrieval process.
"""
print("---CHECK RELEVANCE---")
# Output
class FunctionOutput(BaseModel):
binary_score: str = Field(description="Relevance score 'yes' or 'no'")
# Create an instance of the PydanticOutputParser
parser = PydanticOutputParser(pydantic_object=FunctionOutput)
# Get the format instructions from the output parser
format_instructions = parser.get_format_instructions()
# Create a prompt template with format instructions and the query
prompt = PromptTemplate(
template="""You are a grader assessing relevance of retrieved docs to a user question. \n
Here are the retrieved docs:
\n ------- \n
{context}
\n ------- \n
Here is the user question: {question}
If the docs contain keyword(s) in the user question, then score them as relevant. \n
Give a binary score 'yes' or 'no' score to indicate whether the docs are relevant to the question. \n
Output format instructions: \n {format_instructions}""",
input_variables=["question"],
partial_variables={"format_instructions": format_instructions},
)
model = ChatOpenAI(temperature=0, model="gpt-4-0125-preview")
chain = prompt | model | parser
messages = state["messages"]
last_message = messages[-1]
score = chain.invoke(
{"question": messages[0].content, "context": last_message.content}
)
# If relevant
if score.binary_score == "yes":
print("---DECISION: DOCS RELEVANT---")
return "yes"
else:
print("---DECISION: DOCS NOT RELEVANT---")
print(score.binary_score)
return "no"
### Nodes
# Define the function that calls the model
def call_model(state):
"""
Invokes the agent model to generate a response based on the current state.
This function calls the agent model to generate a response to the current conversation state.
The response is added to the state's messages.
Args:
state (messages): The current state of the agent, including all messages.
Returns:
dict: The updated state with the new message added to the list of messages.
"""
print("---CALL AGENT---")
messages = state["messages"]
model = ChatOpenAI(temperature=0, streaming=True, model="gpt-4-0125-preview")
functions = [format_tool_to_openai_function(t) for t in tools]
model = model.bind_functions(functions)
response = model.invoke(messages)
# We return a list, because this will get added to the existing list
return {"messages": [response]}
# Define the function to execute tools
def retrieve(state):
"""
Executes a tool based on the last message's function call.
This function is responsible for executing a tool invocation based on the function call
specified in the last message. The result from the tool execution is added to the conversation
state as a new message.
Args:
state (messages): The current state of the agent, including all messages.
Returns:
dict: The updated state with the new function message added to the list of messages.
"""
print("---EXECUTE RETRIEVAL---")
messages = state["messages"]
# Based on the continue condition
# we know the last message involves a function call
last_message = messages[-1]
# We construct an ToolInvocation from the function_call
action = ToolInvocation(
tool=last_message.additional_kwargs["function_call"]["name"],
tool_input=json.loads(
last_message.additional_kwargs["function_call"]["arguments"]
),
)
# We call the tool_executor and get back a response
response = tool_executor.invoke(action)
# print(type(response))
# We use the response to create a FunctionMessage
function_message = FunctionMessage(content=str(response), name=action.tool)
# We return a list, because this will get added to the existing list
return {"messages": [function_message]}
# Rewrite query
def rewrite(state):
"""
Transform the query to produce a better question.
Args:
state (messages): The current state of the agent, including all messages.
Returns:
dict: The updated state with the new function message added to the list of messages.
"""
print("---TRANSFORM QUERY---")
# we know the first message involves a user question
question = messages[0]
msg = HumanMessage(
content=f""" \n
Look at the input and try to reason about the underlying semantic intent / meaning. \n
Here is the initial question:
\n ------- \n
{question}
\n ------- \n
Formulate an improved question: """,
)
# Grader
model = ChatOpenAI(temperature=0, model="gpt-4-0125-preview", streaming=True)
response = model.invoke(msg)
return {"messages": [response]}In [28]:
from langgraph.graph import END, StateGraph
# Define a new graph
workflow = StateGraph(AgentState)
# Define the nodes we will cycle between
workflow.add_node("agent", call_model) # agent
workflow.add_node("retrieve", retrieve) # retrieval
workflow.add_node("rewrite", rewrite) # retrievalIn [29]:
# Call agent node to decide to retrieve or not
workflow.set_entry_point("agent")
# Decide whether to retrieve
workflow.add_conditional_edges(
"agent",
# Assess agent decision
should_retrieve,
{
# Call tool node
"continue": "retrieve",
"end": END,
},
)
# Edges taken after the `action` node is called.
workflow.add_conditional_edges(
"retrieve",
# Assess agent decision
check_relevance,
{
# Call agent node
"yes": "agent",
"no": "rewrite",
},
)
workflow.add_edge("agent", END)
workflow.add_edge("rewrite", "agent")
# Compile
app = workflow.compile()In [30]:
inputs = {
"messages": [
HumanMessage(
content="What does Lilian Weng say about the types of agent memory?"
)
]
}
app.invoke(inputs)---CALL AGENT--- ---DECIDE TO RETRIEVE--- ---DECISION: RETRIEVE--- ---EXECUTE RETRIEVAL--- ---CHECK RELEVANCE--- ---DECISION: DOCS RELEVANT--- ---CALL AGENT--- ---DECIDE TO RETRIEVE--- ---DECISION: DO NOT RETRIEVE / DONE---
[0;31m---------------------------------------------------------------------------[0m [0;31mInvalidUpdateError[0m Traceback (most recent call last) File [0;32m~/miniforge3/envs/llama2/lib/python3.9/site-packages/langgraph/pregel/__init__.py:736[0m, in [0;36m_apply_writes[0;34m(checkpoint, channels, pending_writes, config, for_step)[0m [1;32m 735[0m [38;5;28;01mtry[39;00m: [0;32m--> 736[0m [43mchannels[49m[43m[[49m[43mchan[49m[43m][49m[38;5;241;43m.[39;49m[43mupdate[49m[43m([49m[43mvals[49m[43m)[49m [1;32m 737[0m [38;5;28;01mexcept[39;00m InvalidUpdateError [38;5;28;01mas[39;00m e: File [0;32m~/miniforge3/envs/llama2/lib/python3.9/site-packages/langgraph/channels/last_value.py:47[0m, in [0;36mLastValue.update[0;34m(self, values)[0m [1;32m 46[0m [38;5;28;01mif[39;00m [38;5;28mlen[39m(values) [38;5;241m!=[39m [38;5;241m1[39m: [0;32m---> 47[0m [38;5;28;01mraise[39;00m InvalidUpdateError([38;5;124m"[39m[38;5;124mLastValue can only receive one value per step.[39m[38;5;124m"[39m) [1;32m 49[0m [38;5;28mself[39m[38;5;241m.[39mvalue [38;5;241m=[39m values[[38;5;241m-[39m[38;5;241m1[39m] [0;31mInvalidUpdateError[0m: LastValue can only receive one value per step. The above exception was the direct cause of the following exception: [0;31mInvalidUpdateError[0m Traceback (most recent call last) Cell [0;32mIn[30], line 9[0m [1;32m 1[0m inputs [38;5;241m=[39m { [1;32m 2[0m [38;5;124m"[39m[38;5;124mmessages[39m[38;5;124m"[39m: [ [1;32m 3[0m HumanMessage( [0;32m (...)[0m [1;32m 6[0m ] [1;32m 7[0m } [0;32m----> 9[0m [43mapp[49m[38;5;241;43m.[39;49m[43minvoke[49m[43m([49m[43minputs[49m[43m)[49m File [0;32m~/miniforge3/envs/llama2/lib/python3.9/site-packages/langgraph/pregel/__init__.py:569[0m, in [0;36mPregel.invoke[0;34m(self, input, config, output_keys, input_keys, **kwargs)[0m [1;32m 559[0m [38;5;28;01mdef[39;00m [38;5;21minvoke[39m( [1;32m 560[0m [38;5;28mself[39m, [1;32m 561[0m [38;5;28minput[39m: Union[[38;5;28mdict[39m[[38;5;28mstr[39m, Any], Any], [0;32m (...)[0m [1;32m 566[0m [38;5;241m*[39m[38;5;241m*[39mkwargs: Any, [1;32m 567[0m ) [38;5;241m-[39m[38;5;241m>[39m Union[[38;5;28mdict[39m[[38;5;28mstr[39m, Any], Any]: [1;32m 568[0m latest: Union[[38;5;28mdict[39m[[38;5;28mstr[39m, Any], Any] [38;5;241m=[39m [38;5;28;01mNone[39;00m [0;32m--> 569[0m [38;5;28;01mfor[39;00m chunk [38;5;129;01min[39;00m [38;5;28mself[39m[38;5;241m.[39mstream( [1;32m 570[0m [38;5;28minput[39m, [1;32m 571[0m config, [1;32m 572[0m output_keys[38;5;241m=[39moutput_keys [38;5;28;01mif[39;00m output_keys [38;5;129;01mis[39;00m [38;5;129;01mnot[39;00m [38;5;28;01mNone[39;00m [38;5;28;01melse[39;00m [38;5;28mself[39m[38;5;241m.[39moutput, [1;32m 573[0m input_keys[38;5;241m=[39minput_keys, [1;32m 574[0m [38;5;241m*[39m[38;5;241m*[39mkwargs, [1;32m 575[0m ): [1;32m 576[0m latest [38;5;241m=[39m chunk [1;32m 577[0m [38;5;28;01mreturn[39;00m latest File [0;32m~/miniforge3/envs/llama2/lib/python3.9/site-packages/langgraph/pregel/__init__.py:605[0m, in [0;36mPregel.transform[0;34m(self, input, config, output_keys, input_keys, **kwargs)[0m [1;32m 596[0m [38;5;28;01mdef[39;00m [38;5;21mtransform[39m( [1;32m 597[0m [38;5;28mself[39m, [1;32m 598[0m [38;5;28minput[39m: Iterator[Union[[38;5;28mdict[39m[[38;5;28mstr[39m, Any], Any]], [0;32m (...)[0m [1;32m 603[0m [38;5;241m*[39m[38;5;241m*[39mkwargs: Any, [1;32m 604[0m ) [38;5;241m-[39m[38;5;241m>[39m Iterator[Union[[38;5;28mdict[39m[[38;5;28mstr[39m, Any], Any]]: [0;32m--> 605[0m [38;5;28;01mfor[39;00m chunk [38;5;129;01min[39;00m [38;5;28mself[39m[38;5;241m.[39m_transform_stream_with_config( [1;32m 606[0m [38;5;28minput[39m, [1;32m 607[0m [38;5;28mself[39m[38;5;241m.[39m_transform, [1;32m 608[0m config, [1;32m 609[0m output_keys[38;5;241m=[39moutput_keys, [1;32m 610[0m input_keys[38;5;241m=[39minput_keys, [1;32m 611[0m [38;5;241m*[39m[38;5;241m*[39mkwargs, [1;32m 612[0m ): [1;32m 613[0m [38;5;28;01myield[39;00m chunk File [0;32m~/miniforge3/envs/llama2/lib/python3.9/site-packages/langchain_core/runnables/base.py:1497[0m, in [0;36mRunnable._transform_stream_with_config[0;34m(self, input, transformer, config, run_type, **kwargs)[0m [1;32m 1495[0m [38;5;28;01mtry[39;00m: [1;32m 1496[0m [38;5;28;01mwhile[39;00m [38;5;28;01mTrue[39;00m: [0;32m-> 1497[0m chunk: Output [38;5;241m=[39m [43mcontext[49m[38;5;241;43m.[39;49m[43mrun[49m[43m([49m[38;5;28;43mnext[39;49m[43m,[49m[43m [49m[43miterator[49m[43m)[49m [38;5;66;03m# type: ignore[39;00m [1;32m 1498[0m [38;5;28;01myield[39;00m chunk [1;32m 1499[0m [38;5;28;01mif[39;00m final_output_supported: File [0;32m~/miniforge3/envs/llama2/lib/python3.9/site-packages/langgraph/pregel/__init__.py:350[0m, in [0;36mPregel._transform[0;34m(self, input, run_manager, config, input_keys, output_keys)[0m [1;32m 347[0m _interrupt_or_proceed(done, inflight, step) [1;32m 349[0m [38;5;66;03m# apply writes to channels[39;00m [0;32m--> 350[0m [43m_apply_writes[49m[43m([49m [1;32m 351[0m [43m [49m[43mcheckpoint[49m[43m,[49m[43m [49m[43mchannels[49m[43m,[49m[43m [49m[43mpending_writes[49m[43m,[49m[43m [49m[43mconfig[49m[43m,[49m[43m [49m[43mstep[49m[43m [49m[38;5;241;43m+[39;49m[43m [49m[38;5;241;43m1[39;49m [1;32m 352[0m [43m[49m[43m)[49m [1;32m 354[0m [38;5;28;01mif[39;00m [38;5;28mself[39m[38;5;241m.[39mdebug: [1;32m 355[0m print_checkpoint(step, channels) File [0;32m~/miniforge3/envs/llama2/lib/python3.9/site-packages/langgraph/pregel/__init__.py:738[0m, in [0;36m_apply_writes[0;34m(checkpoint, channels, pending_writes, config, for_step)[0m [1;32m 736[0m channels[chan][38;5;241m.[39mupdate(vals) [1;32m 737[0m [38;5;28;01mexcept[39;00m InvalidUpdateError [38;5;28;01mas[39;00m e: [0;32m--> 738[0m [38;5;28;01mraise[39;00m InvalidUpdateError( [1;32m 739[0m [38;5;124mf[39m[38;5;124m"[39m[38;5;124mInvalid update for channel [39m[38;5;132;01m{[39;00mchan[38;5;132;01m}[39;00m[38;5;124m: [39m[38;5;132;01m{[39;00me[38;5;132;01m}[39;00m[38;5;124m"[39m [1;32m 740[0m ) [38;5;28;01mfrom[39;00m [38;5;21;01me[39;00m [1;32m 741[0m checkpoint[[38;5;124m"[39m[38;5;124mchannel_versions[39m[38;5;124m"[39m][chan] [38;5;241m+[39m[38;5;241m=[39m [38;5;241m1[39m [1;32m 742[0m updated_channels[38;5;241m.[39madd(chan) [0;31mInvalidUpdateError[0m: Invalid update for channel __end__: LastValue can only receive one value per step.
In [22]:
import pprint
from langchain_core.messages import HumanMessage
inputs = {
"messages": [
HumanMessage(
content="What does Lilian Weng say about the types of agent memory?"
)
]
}
for output in app.stream(inputs):
for key, value in output.items():
pprint.pprint(f"Output from node '{key}':")
pprint.pprint("---")
pprint.pprint(value, indent=2, width=80, depth=None)
pprint.pprint("\n---\n")---CALL AGENT---
"Output from node 'agent':"
'---'
{ 'messages': [ AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"query":"types of agent memory"}', 'name': 'retrieve_blog_posts'}})]}
'\n---\n'
---DECIDE TO RETRIEVE---
---DECISION: RETRIEVE---
"Output from node '__end__':"
'---'
{ 'messages': [ HumanMessage(content='What does Lilian Weng say about the types of agent memory?'),
AIMessage(content='', additional_kwargs={'function_call': {'arguments': '{"query":"types of agent memory"}', 'name': 'retrieve_blog_posts'}})]}
'\n---\n'
---EXECUTE RETRIEVAL---
"Output from node 'retrieve':"
'---'
{ 'messages': [ FunctionMessage(content='Table of Contents\n\n\n\nAgent System Overview\n\nComponent One: Planning\n\nTask Decomposition\n\nSelf-Reflection\n\n\nComponent Two: Memory\n\nTypes of Memory\n\nMaximum Inner Product Search (MIPS)\n\n\nComponent Three: Tool Use\n\nCase Studies\n\nScientific Discovery Agent\n\nGenerative Agents Simulation\n\nProof-of-Concept Examples\n\n\nChallenges\n\nCitation\n\nReferences\n\nTable of Contents\n\n\n\nAgent System Overview\n\nComponent One: Planning\n\nTask Decomposition\n\nSelf-Reflection\n\n\nComponent Two: Memory\n\nTypes of Memory\n\nMaximum Inner Product Search (MIPS)\n\n\nComponent Three: Tool Use\n\nCase Studies\n\nScientific Discovery Agent\n\nGenerative Agents Simulation\n\nProof-of-Concept Examples\n\n\nChallenges\n\nCitation\n\nReferences\n\nPlanning\n\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\n\n\nMemory\n\nPlanning\n\nSubgoal and decomposition: The agent breaks down large tasks into smaller, manageable subgoals, enabling efficient handling of complex tasks.\nReflection and refinement: The agent can do self-criticism and self-reflection over past actions, learn from mistakes and refine them for future steps, thereby improving the quality of final results.\n\n\nMemory', name='retrieve_blog_posts')]}
'\n---\n'
---CHECK RELEVANCE---
---DECISION: DOCS RELEVANT---
---CALL AGENT---
"Output from node 'agent':"
'---'
{ 'messages': [ AIMessage(content='Lilian Weng discusses the concept of memory within agent systems, highlighting its importance but does not provide specific details on the types of agent memory in the provided excerpt. The discussion on memory is part of a broader overview of agent systems, which also includes planning and tool use. In the context of planning, agents are capable of breaking down large tasks into smaller, manageable subgoals (task decomposition) and engaging in self-reflection and refinement based on past actions to improve future outcomes.\n\nWhile the excerpt mentions a section titled "Types of Memory," specific details or descriptions of these types are not provided in the provided content. Additionally, there\'s a mention of Maximum Inner Product Search (MIPS) in the context of memory, suggesting it might be a technique or tool related to how agents access or utilize their memory, but again, specific details are not given.\n\nFor a more detailed understanding of the types of agent memory Lilian Weng discusses, it would be necessary to access the full content of her blog post or publication.')]}
'\n---\n'
---DECIDE TO RETRIEVE---
---DECISION: DO NOT RETRIEVE / DONE---
[0;31m---------------------------------------------------------------------------[0m [0;31mInvalidUpdateError[0m Traceback (most recent call last) File [0;32m~/miniforge3/envs/llama2/lib/python3.9/site-packages/langgraph/pregel/__init__.py:736[0m, in [0;36m_apply_writes[0;34m(checkpoint, channels, pending_writes, config, for_step)[0m [1;32m 735[0m [38;5;28;01mtry[39;00m: [0;32m--> 736[0m [43mchannels[49m[43m[[49m[43mchan[49m[43m][49m[38;5;241;43m.[39;49m[43mupdate[49m[43m([49m[43mvals[49m[43m)[49m [1;32m 737[0m [38;5;28;01mexcept[39;00m InvalidUpdateError [38;5;28;01mas[39;00m e: File [0;32m~/miniforge3/envs/llama2/lib/python3.9/site-packages/langgraph/channels/last_value.py:47[0m, in [0;36mLastValue.update[0;34m(self, values)[0m [1;32m 46[0m [38;5;28;01mif[39;00m [38;5;28mlen[39m(values) [38;5;241m!=[39m [38;5;241m1[39m: [0;32m---> 47[0m [38;5;28;01mraise[39;00m InvalidUpdateError([38;5;124m"[39m[38;5;124mLastValue can only receive one value per step.[39m[38;5;124m"[39m) [1;32m 49[0m [38;5;28mself[39m[38;5;241m.[39mvalue [38;5;241m=[39m values[[38;5;241m-[39m[38;5;241m1[39m] [0;31mInvalidUpdateError[0m: LastValue can only receive one value per step. The above exception was the direct cause of the following exception: [0;31mInvalidUpdateError[0m Traceback (most recent call last) Cell [0;32mIn[22], line 12[0m [1;32m 3[0m [38;5;28;01mfrom[39;00m [38;5;21;01mlangchain_core[39;00m[38;5;21;01m.[39;00m[38;5;21;01mmessages[39;00m [38;5;28;01mimport[39;00m HumanMessage [1;32m 5[0m inputs [38;5;241m=[39m { [1;32m 6[0m [38;5;124m"[39m[38;5;124mmessages[39m[38;5;124m"[39m: [ [1;32m 7[0m HumanMessage( [0;32m (...)[0m [1;32m 10[0m ] [1;32m 11[0m } [0;32m---> 12[0m [38;5;28;01mfor[39;00m output [38;5;129;01min[39;00m app[38;5;241m.[39mstream(inputs): [1;32m 13[0m [38;5;28;01mfor[39;00m key, value [38;5;129;01min[39;00m output[38;5;241m.[39mitems(): [1;32m 14[0m pprint[38;5;241m.[39mpprint([38;5;124mf[39m[38;5;124m"[39m[38;5;124mOutput from node [39m[38;5;124m'[39m[38;5;132;01m{[39;00mkey[38;5;132;01m}[39;00m[38;5;124m'[39m[38;5;124m:[39m[38;5;124m"[39m) File [0;32m~/miniforge3/envs/llama2/lib/python3.9/site-packages/langgraph/pregel/__init__.py:605[0m, in [0;36mPregel.transform[0;34m(self, input, config, output_keys, input_keys, **kwargs)[0m [1;32m 596[0m [38;5;28;01mdef[39;00m [38;5;21mtransform[39m( [1;32m 597[0m [38;5;28mself[39m, [1;32m 598[0m [38;5;28minput[39m: Iterator[Union[[38;5;28mdict[39m[[38;5;28mstr[39m, Any], Any]], [0;32m (...)[0m [1;32m 603[0m [38;5;241m*[39m[38;5;241m*[39mkwargs: Any, [1;32m 604[0m ) [38;5;241m-[39m[38;5;241m>[39m Iterator[Union[[38;5;28mdict[39m[[38;5;28mstr[39m, Any], Any]]: [0;32m--> 605[0m [38;5;28;01mfor[39;00m chunk [38;5;129;01min[39;00m [38;5;28mself[39m[38;5;241m.[39m_transform_stream_with_config( [1;32m 606[0m [38;5;28minput[39m, [1;32m 607[0m [38;5;28mself[39m[38;5;241m.[39m_transform, [1;32m 608[0m config, [1;32m 609[0m output_keys[38;5;241m=[39moutput_keys, [1;32m 610[0m input_keys[38;5;241m=[39minput_keys, [1;32m 611[0m [38;5;241m*[39m[38;5;241m*[39mkwargs, [1;32m 612[0m ): [1;32m 613[0m [38;5;28;01myield[39;00m chunk File [0;32m~/miniforge3/envs/llama2/lib/python3.9/site-packages/langchain_core/runnables/base.py:1497[0m, in [0;36mRunnable._transform_stream_with_config[0;34m(self, input, transformer, config, run_type, **kwargs)[0m [1;32m 1495[0m [38;5;28;01mtry[39;00m: [1;32m 1496[0m [38;5;28;01mwhile[39;00m [38;5;28;01mTrue[39;00m: [0;32m-> 1497[0m chunk: Output [38;5;241m=[39m [43mcontext[49m[38;5;241;43m.[39;49m[43mrun[49m[43m([49m[38;5;28;43mnext[39;49m[43m,[49m[43m [49m[43miterator[49m[43m)[49m [38;5;66;03m# type: ignore[39;00m [1;32m 1498[0m [38;5;28;01myield[39;00m chunk [1;32m 1499[0m [38;5;28;01mif[39;00m final_output_supported: File [0;32m~/miniforge3/envs/llama2/lib/python3.9/site-packages/langgraph/pregel/__init__.py:350[0m, in [0;36mPregel._transform[0;34m(self, input, run_manager, config, input_keys, output_keys)[0m [1;32m 347[0m _interrupt_or_proceed(done, inflight, step) [1;32m 349[0m [38;5;66;03m# apply writes to channels[39;00m [0;32m--> 350[0m [43m_apply_writes[49m[43m([49m [1;32m 351[0m [43m [49m[43mcheckpoint[49m[43m,[49m[43m [49m[43mchannels[49m[43m,[49m[43m [49m[43mpending_writes[49m[43m,[49m[43m [49m[43mconfig[49m[43m,[49m[43m [49m[43mstep[49m[43m [49m[38;5;241;43m+[39;49m[43m [49m[38;5;241;43m1[39;49m [1;32m 352[0m [43m[49m[43m)[49m [1;32m 354[0m [38;5;28;01mif[39;00m [38;5;28mself[39m[38;5;241m.[39mdebug: [1;32m 355[0m print_checkpoint(step, channels) File [0;32m~/miniforge3/envs/llama2/lib/python3.9/site-packages/langgraph/pregel/__init__.py:738[0m, in [0;36m_apply_writes[0;34m(checkpoint, channels, pending_writes, config, for_step)[0m [1;32m 736[0m channels[chan][38;5;241m.[39mupdate(vals) [1;32m 737[0m [38;5;28;01mexcept[39;00m InvalidUpdateError [38;5;28;01mas[39;00m e: [0;32m--> 738[0m [38;5;28;01mraise[39;00m InvalidUpdateError( [1;32m 739[0m [38;5;124mf[39m[38;5;124m"[39m[38;5;124mInvalid update for channel [39m[38;5;132;01m{[39;00mchan[38;5;132;01m}[39;00m[38;5;124m: [39m[38;5;132;01m{[39;00me[38;5;132;01m}[39;00m[38;5;124m"[39m [1;32m 740[0m ) [38;5;28;01mfrom[39;00m [38;5;21;01me[39;00m [1;32m 741[0m checkpoint[[38;5;124m"[39m[38;5;124mchannel_versions[39m[38;5;124m"[39m][chan] [38;5;241m+[39m[38;5;241m=[39m [38;5;241m1[39m [1;32m 742[0m updated_channels[38;5;241m.[39madd(chan) [0;31mInvalidUpdateError[0m: Invalid update for channel __end__: LastValue can only receive one value per step.
In [ ]:
