From e9a7ad8b69d1d4438b8fa46e5abeda8c6bde5500 Mon Sep 17 00:00:00 2001 From: William Fu-Hinthorn <13333726+hinthornw@users.noreply.github.com> Date: Thu, 15 Feb 2024 23:09:59 -0800 Subject: [PATCH] Format --- examples/agent_executor/base.ipynb | 35 +++++++------ .../force-calling-a-tool-first.ipynb | 50 ++++++++++--------- examples/agent_executor/high-level.ipynb | 17 ++++--- .../agent_executor/human-in-the-loop.ipynb | 34 +++++++------ .../agent_executor/managing-agent-steps.ipynb | 38 +++++++------- examples/async.ipynb | 20 +++++--- .../base.ipynb | 20 +++++--- .../dynamically-returning-directly.ipynb | 35 ++++++++----- .../force-calling-a-tool-first.ipynb | 37 ++++++++------ .../human-in-the-loop.ipynb | 19 ++++--- .../managing-agent-steps.ipynb | 18 ++++--- .../respond-in-format.ipynb | 22 +++++--- .../agent-simulation-evaluation.ipynb | 8 +-- examples/human-in-the-loop.ipynb | 17 +++++-- examples/persistence.ipynb | 15 ++++-- examples/rag/langgraph_crag.ipynb | 12 +++-- examples/rag/langgraph_crag_mistral.ipynb | 6 +-- examples/rag/langgraph_self_rag.ipynb | 4 +- examples/self-discover/self-discover.ipynb | 16 +++--- examples/streaming-tokens.ipynb | 15 ++++-- 20 files changed, 265 insertions(+), 173 deletions(-) diff --git a/examples/agent_executor/base.ipynb b/examples/agent_executor/base.ipynb index 1e2077740..87fcbee9a 100644 --- a/examples/agent_executor/base.ipynb +++ b/examples/agent_executor/base.ipynb @@ -133,17 +133,17 @@ "\n", "\n", "class AgentState(TypedDict):\n", - " # The input string\n", - " input: str\n", - " # The list of previous messages in the conversation\n", - " chat_history: list[BaseMessage]\n", - " # The outcome of a given call to the agent\n", - " # Needs `None` as a valid type, since this is what this will start as\n", - " agent_outcome: Union[AgentAction, AgentFinish, None]\n", - " # List of actions and corresponding observations\n", - " # Here we annotate this with `operator.add` to indicate that operations to\n", - " # this state should be ADDED to the existing values (not overwrite it)\n", - " intermediate_steps: Annotated[list[tuple[AgentAction, str]], operator.add]\n" + " # The input string\n", + " input: str\n", + " # The list of previous messages in the conversation\n", + " chat_history: list[BaseMessage]\n", + " # The outcome of a given call to the agent\n", + " # Needs `None` as a valid type, since this is what this will start as\n", + " agent_outcome: Union[AgentAction, AgentFinish, None]\n", + " # List of actions and corresponding observations\n", + " # Here we annotate this with `operator.add` to indicate that operations to\n", + " # this state should be ADDED to the existing values (not overwrite it)\n", + " intermediate_steps: Annotated[list[tuple[AgentAction, str]], operator.add]" ] }, { @@ -187,23 +187,26 @@ "# It takes in an agent action and calls that tool and returns the result\n", "tool_executor = ToolExecutor(tools)\n", "\n", + "\n", "# Define the agent\n", "def run_agent(data):\n", " agent_outcome = agent_runnable.invoke(data)\n", " return {\"agent_outcome\": agent_outcome}\n", "\n", + "\n", "# Define the function to execute tools\n", "def execute_tools(data):\n", " # Get the most recent agent_outcome - this is the key added in the `agent` above\n", - " agent_action = data['agent_outcome']\n", + " agent_action = data[\"agent_outcome\"]\n", " output = tool_executor.invoke(agent_action)\n", " return {\"intermediate_steps\": [(agent_action, str(output))]}\n", "\n", + "\n", "# Define logic that will be used to determine which conditional edge to go down\n", "def should_continue(data):\n", " # If the agent outcome is an AgentFinish, then we return `exit` string\n", " # This will be used when setting up the graph to define the flow\n", - " if isinstance(data['agent_outcome'], AgentFinish):\n", + " if isinstance(data[\"agent_outcome\"], AgentFinish):\n", " return \"end\"\n", " # Otherwise, an AgentAction is returned\n", " # Here we return `continue` string\n", @@ -259,13 +262,13 @@ " # If `tools`, then we call the tool node.\n", " \"continue\": \"action\",\n", " # Otherwise we finish.\n", - " \"end\": END\n", - " }\n", + " \"end\": END,\n", + " },\n", ")\n", "\n", "# We now add a normal edge from `tools` to `agent`.\n", "# This means that after `tools` is called, `agent` node is called next.\n", - "workflow.add_edge('action', 'agent')\n", + "workflow.add_edge(\"action\", \"agent\")\n", "\n", "# Finally, we compile it!\n", "# This compiles it into a LangChain Runnable,\n", diff --git a/examples/agent_executor/force-calling-a-tool-first.ipynb b/examples/agent_executor/force-calling-a-tool-first.ipynb index 49dccc319..74ca4664d 100644 --- a/examples/agent_executor/force-calling-a-tool-first.ipynb +++ b/examples/agent_executor/force-calling-a-tool-first.ipynb @@ -138,17 +138,17 @@ "\n", "\n", "class AgentState(TypedDict):\n", - " # The input string\n", - " input: str\n", - " # The list of previous messages in the conversation\n", - " chat_history: list[BaseMessage]\n", - " # The outcome of a given call to the agent\n", - " # Needs `None` as a valid type, since this is what this will start as\n", - " agent_outcome: Union[AgentAction, AgentFinish, None]\n", - " # List of actions and corresponding observations\n", - " # Here we annotate this with `operator.add` to indicate that operations to\n", - " # this state should be ADDED to the existing values (not overwrite it)\n", - " intermediate_steps: Annotated[list[tuple[AgentAction, str]], operator.add]\n" + " # The input string\n", + " input: str\n", + " # The list of previous messages in the conversation\n", + " chat_history: list[BaseMessage]\n", + " # The outcome of a given call to the agent\n", + " # Needs `None` as a valid type, since this is what this will start as\n", + " agent_outcome: Union[AgentAction, AgentFinish, None]\n", + " # List of actions and corresponding observations\n", + " # Here we annotate this with `operator.add` to indicate that operations to\n", + " # this state should be ADDED to the existing values (not overwrite it)\n", + " intermediate_steps: Annotated[list[tuple[AgentAction, str]], operator.add]" ] }, { @@ -192,23 +192,26 @@ "# It takes in an agent action and calls that tool and returns the result\n", "tool_executor = ToolExecutor(tools)\n", "\n", + "\n", "# Define the agent\n", "def run_agent(data):\n", " agent_outcome = agent_runnable.invoke(data)\n", " return {\"agent_outcome\": agent_outcome}\n", "\n", + "\n", "# Define the function to execute tools\n", "def execute_tools(data):\n", " # Get the most recent agent_outcome - this is the key added in the `agent` above\n", - " agent_action = data['agent_outcome']\n", + " agent_action = data[\"agent_outcome\"]\n", " output = tool_executor.invoke(agent_action)\n", " return {\"intermediate_steps\": [(agent_action, str(output))]}\n", "\n", + "\n", "# Define logic that will be used to determine which conditional edge to go down\n", "def should_continue(data):\n", " # If the agent outcome is an AgentFinish, then we return `exit` string\n", " # This will be used when setting up the graph to define the flow\n", - " if isinstance(data['agent_outcome'], AgentFinish):\n", + " if isinstance(data[\"agent_outcome\"], AgentFinish):\n", " return \"end\"\n", " # Otherwise, an AgentAction is returned\n", " # Here we return `continue` string\n", @@ -257,14 +260,15 @@ "source": [ "from langchain_core.agents import AgentActionMessageLog\n", "\n", + "\n", "def first_agent(inputs):\n", " action = AgentActionMessageLog(\n", - " # We force call this tool\n", - " tool=\"tavily_search_results_json\",\n", - " # We just pass in the `input` key to this tool\n", - " tool_input=inputs[\"input\"],\n", - " log=\"\",\n", - " message_log=[]\n", + " # We force call this tool\n", + " tool=\"tavily_search_results_json\",\n", + " # We just pass in the `input` key to this tool\n", + " tool_input=inputs[\"input\"],\n", + " log=\"\",\n", + " message_log=[],\n", " )\n", " return {\"agent_outcome\": action}" ] @@ -321,16 +325,16 @@ " # If `tools`, then we call the tool node.\n", " \"continue\": \"action\",\n", " # Otherwise we finish.\n", - " \"end\": END\n", - " }\n", + " \"end\": END,\n", + " },\n", ")\n", "\n", "# We now add a normal edge from `tools` to `agent`.\n", "# This means that after `tools` is called, `agent` node is called next.\n", - "workflow.add_edge('action', 'agent')\n", + "workflow.add_edge(\"action\", \"agent\")\n", "\n", "# After the first agent, we want to take an action\n", - "workflow.add_edge('first_agent', 'action')\n", + "workflow.add_edge(\"first_agent\", \"action\")\n", "\n", "# Finally, we compile it!\n", "# This compiles it into a LangChain Runnable,\n", diff --git a/examples/agent_executor/high-level.ipynb b/examples/agent_executor/high-level.ipynb index 1922e5ab7..ec3082221 100644 --- a/examples/agent_executor/high-level.ipynb +++ b/examples/agent_executor/high-level.ipynb @@ -192,7 +192,7 @@ } ], "source": [ - "s['__end__']['agent_outcome']" + "s[\"__end__\"][\"agent_outcome\"]" ] }, { @@ -226,10 +226,15 @@ "source": [ "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n", "\n", - "prompt = ChatPromptTemplate.from_messages([\n", - " (\"human\", \"Respond to the user question: {question}. Answer in this language: {language}\"),\n", - " MessagesPlaceholder(variable_name=\"agent_scratchpad\")\n", - "])\n", + "prompt = ChatPromptTemplate.from_messages(\n", + " [\n", + " (\n", + " \"human\",\n", + " \"Respond to the user question: {question}. Answer in this language: {language}\",\n", + " ),\n", + " MessagesPlaceholder(variable_name=\"agent_scratchpad\"),\n", + " ]\n", + ")\n", "agent_runnable = create_openai_functions_agent(llm, tools, prompt)" ] }, @@ -327,7 +332,7 @@ } ], "source": [ - "s['__end__']['agent_outcome']" + "s[\"__end__\"][\"agent_outcome\"]" ] }, { diff --git a/examples/agent_executor/human-in-the-loop.ipynb b/examples/agent_executor/human-in-the-loop.ipynb index d52ad06e2..ea3cf4705 100644 --- a/examples/agent_executor/human-in-the-loop.ipynb +++ b/examples/agent_executor/human-in-the-loop.ipynb @@ -138,17 +138,17 @@ "\n", "\n", "class AgentState(TypedDict):\n", - " # The input string\n", - " input: str\n", - " # The list of previous messages in the conversation\n", - " chat_history: list[BaseMessage]\n", - " # The outcome of a given call to the agent\n", - " # Needs `None` as a valid type, since this is what this will start as\n", - " agent_outcome: Union[AgentAction, AgentFinish, None]\n", - " # List of actions and corresponding observations\n", - " # Here we annotate this with `operator.add` to indicate that operations to\n", - " # this state should be ADDED to the existing values (not overwrite it)\n", - " intermediate_steps: Annotated[list[tuple[AgentAction, str]], operator.add]\n" + " # The input string\n", + " input: str\n", + " # The list of previous messages in the conversation\n", + " chat_history: list[BaseMessage]\n", + " # The outcome of a given call to the agent\n", + " # Needs `None` as a valid type, since this is what this will start as\n", + " agent_outcome: Union[AgentAction, AgentFinish, None]\n", + " # List of actions and corresponding observations\n", + " # Here we annotate this with `operator.add` to indicate that operations to\n", + " # this state should be ADDED to the existing values (not overwrite it)\n", + " intermediate_steps: Annotated[list[tuple[AgentAction, str]], operator.add]" ] }, { @@ -192,6 +192,7 @@ "# It takes in an agent action and calls that tool and returns the result\n", "tool_executor = ToolExecutor(tools)\n", "\n", + "\n", "# Define the agent\n", "def run_agent(data):\n", " agent_outcome = agent_runnable.invoke(data)\n", @@ -218,18 +219,19 @@ "# Define the function to execute tools\n", "def execute_tools(data):\n", " # Get the most recent agent_outcome - this is the key added in the `agent` above\n", - " agent_action = data['agent_outcome']\n", + " agent_action = data[\"agent_outcome\"]\n", " response = input(prompt=f\"[y/n] continue with: {agent_action}?\")\n", " if response == \"n\":\n", " raise ValueError\n", " output = tool_executor.invoke(agent_action)\n", " return {\"intermediate_steps\": [(agent_action, str(output))]}\n", "\n", + "\n", "# Define logic that will be used to determine which conditional edge to go down\n", "def should_continue(data):\n", " # If the agent outcome is an AgentFinish, then we return `exit` string\n", " # This will be used when setting up the graph to define the flow\n", - " if isinstance(data['agent_outcome'], AgentFinish):\n", + " if isinstance(data[\"agent_outcome\"], AgentFinish):\n", " return \"end\"\n", " # Otherwise, an AgentAction is returned\n", " # Here we return `continue` string\n", @@ -285,13 +287,13 @@ " # If `tools`, then we call the tool node.\n", " \"continue\": \"action\",\n", " # Otherwise we finish.\n", - " \"end\": END\n", - " }\n", + " \"end\": END,\n", + " },\n", ")\n", "\n", "# We now add a normal edge from `tools` to `agent`.\n", "# This means that after `tools` is called, `agent` node is called next.\n", - "workflow.add_edge('action', 'agent')\n", + "workflow.add_edge(\"action\", \"agent\")\n", "\n", "# Finally, we compile it!\n", "# This compiles it into a LangChain Runnable,\n", diff --git a/examples/agent_executor/managing-agent-steps.ipynb b/examples/agent_executor/managing-agent-steps.ipynb index d509d8f8d..31847fe67 100644 --- a/examples/agent_executor/managing-agent-steps.ipynb +++ b/examples/agent_executor/managing-agent-steps.ipynb @@ -138,17 +138,17 @@ "\n", "\n", "class AgentState(TypedDict):\n", - " # The input string\n", - " input: str\n", - " # The list of previous messages in the conversation\n", - " chat_history: list[BaseMessage]\n", - " # The outcome of a given call to the agent\n", - " # Needs `None` as a valid type, since this is what this will start as\n", - " agent_outcome: Union[AgentAction, AgentFinish, None]\n", - " # List of actions and corresponding observations\n", - " # Here we annotate this with `operator.add` to indicate that operations to\n", - " # this state should be ADDED to the existing values (not overwrite it)\n", - " intermediate_steps: Annotated[list[tuple[AgentAction, str]], operator.add]\n" + " # The input string\n", + " input: str\n", + " # The list of previous messages in the conversation\n", + " chat_history: list[BaseMessage]\n", + " # The outcome of a given call to the agent\n", + " # Needs `None` as a valid type, since this is what this will start as\n", + " agent_outcome: Union[AgentAction, AgentFinish, None]\n", + " # List of actions and corresponding observations\n", + " # Here we annotate this with `operator.add` to indicate that operations to\n", + " # this state should be ADDED to the existing values (not overwrite it)\n", + " intermediate_steps: Annotated[list[tuple[AgentAction, str]], operator.add]" ] }, { @@ -213,23 +213,25 @@ "# Define the agent\n", "def run_agent(data):\n", " inputs = data.copy()\n", - " if len(inputs['intermediate_steps']) > 5:\n", - " inputs['intermediate_steps'] = inputs['intermediate_steps'][-5:]\n", + " if len(inputs[\"intermediate_steps\"]) > 5:\n", + " inputs[\"intermediate_steps\"] = inputs[\"intermediate_steps\"][-5:]\n", " agent_outcome = agent_runnable.invoke(inputs)\n", " return {\"agent_outcome\": agent_outcome}\n", "\n", + "\n", "# Define the function to execute tools\n", "def execute_tools(data):\n", " # Get the most recent agent_outcome - this is the key added in the `agent` above\n", - " agent_action = data['agent_outcome']\n", + " agent_action = data[\"agent_outcome\"]\n", " output = tool_executor.invoke(agent_action)\n", " return {\"intermediate_steps\": [(agent_action, str(output))]}\n", "\n", + "\n", "# Define logic that will be used to determine which conditional edge to go down\n", "def should_continue(data):\n", " # If the agent outcome is an AgentFinish, then we return `exit` string\n", " # This will be used when setting up the graph to define the flow\n", - " if isinstance(data['agent_outcome'], AgentFinish):\n", + " if isinstance(data[\"agent_outcome\"], AgentFinish):\n", " return \"end\"\n", " # Otherwise, an AgentAction is returned\n", " # Here we return `continue` string\n", @@ -285,13 +287,13 @@ " # If `tools`, then we call the tool node.\n", " \"continue\": \"action\",\n", " # Otherwise we finish.\n", - " \"end\": END\n", - " }\n", + " \"end\": END,\n", + " },\n", ")\n", "\n", "# We now add a normal edge from `tools` to `agent`.\n", "# This means that after `tools` is called, `agent` node is called next.\n", - "workflow.add_edge('action', 'agent')\n", + "workflow.add_edge(\"action\", \"agent\")\n", "\n", "# Finally, we compile it!\n", "# This compiles it into a LangChain Runnable,\n", diff --git a/examples/async.ipynb b/examples/async.ipynb index 7d4a8081c..7c9381db9 100644 --- a/examples/async.ipynb +++ b/examples/async.ipynb @@ -265,9 +265,10 @@ "import json\n", "from langchain_core.messages import FunctionMessage\n", "\n", + "\n", "# Define the function that determines whether to continue or not\n", "def should_continue(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " last_message = messages[-1]\n", " # If there is no function call, then we finish\n", " if \"function_call\" not in last_message.additional_kwargs:\n", @@ -276,23 +277,27 @@ " else:\n", " return \"continue\"\n", "\n", + "\n", "# Define the function that calls the model\n", "async def call_model(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " response = await model.ainvoke(messages)\n", " # We return a list, because this will get added to the existing list\n", " return {\"messages\": [response]}\n", "\n", + "\n", "# Define the function to execute tools\n", "async def call_tool(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " # Based on the continue condition\n", " # we know the last message involves a function call\n", " last_message = messages[-1]\n", " # We construct an ToolInvocation from the function_call\n", " action = ToolInvocation(\n", " tool=last_message.additional_kwargs[\"function_call\"][\"name\"],\n", - " tool_input=json.loads(last_message.additional_kwargs[\"function_call\"][\"arguments\"]),\n", + " tool_input=json.loads(\n", + " last_message.additional_kwargs[\"function_call\"][\"arguments\"]\n", + " ),\n", " )\n", " # We call the tool_executor and get back a response\n", " response = await tool_executor.ainvoke(action)\n", @@ -320,6 +325,7 @@ "outputs": [], "source": [ "from langgraph.graph import StateGraph, END\n", + "\n", "# Define a new graph\n", "workflow = StateGraph(AgentState)\n", "\n", @@ -348,13 +354,13 @@ " # If `tools`, then we call the tool node.\n", " \"continue\": \"action\",\n", " # Otherwise we finish.\n", - " \"end\": END\n", - " }\n", + " \"end\": END,\n", + " },\n", ")\n", "\n", "# We now add a normal edge from `tools` to `agent`.\n", "# This means that after `tools` is called, `agent` node is called next.\n", - "workflow.add_edge('action', 'agent')\n", + "workflow.add_edge(\"action\", \"agent\")\n", "\n", "# Finally, we compile it!\n", "# This compiles it into a LangChain Runnable,\n", diff --git a/examples/chat_agent_executor_with_function_calling/base.ipynb b/examples/chat_agent_executor_with_function_calling/base.ipynb index d6dd885e1..a76a06ae3 100644 --- a/examples/chat_agent_executor_with_function_calling/base.ipynb +++ b/examples/chat_agent_executor_with_function_calling/base.ipynb @@ -242,9 +242,10 @@ "import json\n", "from langchain_core.messages import FunctionMessage\n", "\n", + "\n", "# Define the function that determines whether to continue or not\n", "def should_continue(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " last_message = messages[-1]\n", " # If there is no function call, then we finish\n", " if \"function_call\" not in last_message.additional_kwargs:\n", @@ -253,23 +254,27 @@ " else:\n", " return \"continue\"\n", "\n", + "\n", "# Define the function that calls the model\n", "def call_model(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " response = model.invoke(messages)\n", " # We return a list, because this will get added to the existing list\n", " return {\"messages\": [response]}\n", "\n", + "\n", "# Define the function to execute tools\n", "def call_tool(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " # Based on the continue condition\n", " # we know the last message involves a function call\n", " last_message = messages[-1]\n", " # We construct an ToolInvocation from the function_call\n", " action = ToolInvocation(\n", " tool=last_message.additional_kwargs[\"function_call\"][\"name\"],\n", - " tool_input=json.loads(last_message.additional_kwargs[\"function_call\"][\"arguments\"]),\n", + " tool_input=json.loads(\n", + " last_message.additional_kwargs[\"function_call\"][\"arguments\"]\n", + " ),\n", " )\n", " # We call the tool_executor and get back a response\n", " response = tool_executor.invoke(action)\n", @@ -297,6 +302,7 @@ "outputs": [], "source": [ "from langgraph.graph import StateGraph, END\n", + "\n", "# Define a new graph\n", "workflow = StateGraph(AgentState)\n", "\n", @@ -325,13 +331,13 @@ " # If `tools`, then we call the tool node.\n", " \"continue\": \"action\",\n", " # Otherwise we finish.\n", - " \"end\": END\n", - " }\n", + " \"end\": END,\n", + " },\n", ")\n", "\n", "# We now add a normal edge from `tools` to `agent`.\n", "# This means that after `tools` is called, `agent` node is called next.\n", - "workflow.add_edge('action', 'agent')\n", + "workflow.add_edge(\"action\", \"agent\")\n", "\n", "# Finally, we compile it!\n", "# This compiles it into a LangChain Runnable,\n", diff --git a/examples/chat_agent_executor_with_function_calling/dynamically-returning-directly.ipynb b/examples/chat_agent_executor_with_function_calling/dynamically-returning-directly.ipynb index 0b42ce534..b83c06c30 100644 --- a/examples/chat_agent_executor_with_function_calling/dynamically-returning-directly.ipynb +++ b/examples/chat_agent_executor_with_function_calling/dynamically-returning-directly.ipynb @@ -100,12 +100,14 @@ "source": [ "from langchain_core.pydantic_v1 import BaseModel, Field\n", "\n", + "\n", "class SearchTool(BaseModel):\n", " \"\"\"Look up things online, optionally returning directly\"\"\"\n", + "\n", " query: str = Field(description=\"query to look up online\")\n", - " return_direct: bool = Field(\n", - " description=\"Whether or the result of this should be returned directly to the user without you seeing what it is\", \n", - " default = False\n", + " return_direct: bool = Field(\n", + " description=\"Whether or the result of this should be returned directly to the user without you seeing what it is\",\n", + " default=False,\n", " )" ] }, @@ -289,14 +291,16 @@ "source": [ "# Define the function that determines whether to continue or not\n", "def should_continue(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " last_message = messages[-1]\n", " # If there is no function call, then we finish\n", " if \"function_call\" not in last_message.additional_kwargs:\n", " return \"end\"\n", " # Otherwise if there is, we check if it's suppose to return direct\n", " else:\n", - " arguments = json.loads(last_message.additional_kwargs[\"function_call\"][\"arguments\"])\n", + " arguments = json.loads(\n", + " last_message.additional_kwargs[\"function_call\"][\"arguments\"]\n", + " )\n", " if arguments.get(\"return_direct\", False):\n", " return \"final\"\n", " else:\n", @@ -312,7 +316,7 @@ "source": [ "# Define the function that calls the model\n", "def call_model(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " response = model.invoke(messages)\n", " # We return a list, because this will get added to the existing list\n", " return {\"messages\": [response]}" @@ -337,7 +341,7 @@ "source": [ "# Define the function to execute tools\n", "def call_tool(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " # Based on the continue condition\n", " # we know the last message involves a function call\n", " last_message = messages[-1]\n", @@ -381,6 +385,7 @@ "outputs": [], "source": [ "from langgraph.graph import StateGraph, END\n", + "\n", "# Define a new graph\n", "workflow = StateGraph(AgentState)\n", "\n", @@ -412,14 +417,14 @@ " # Final call\n", " \"final\": \"final\",\n", " # Otherwise we finish.\n", - " \"end\": END\n", - " }\n", + " \"end\": END,\n", + " },\n", ")\n", "\n", "# We now add a normal edge from `tools` to `agent`.\n", "# This means that after `tools` is called, `agent` node is called next.\n", - "workflow.add_edge('action', 'agent')\n", - "workflow.add_edge('final', END)\n", + "workflow.add_edge(\"action\", \"agent\")\n", + "workflow.add_edge(\"final\", END)\n", "\n", "# Finally, we compile it!\n", "# This compiles it into a LangChain Runnable,\n", @@ -522,7 +527,13 @@ "source": [ "from langchain_core.messages import HumanMessage\n", "\n", - "inputs = {\"messages\": [HumanMessage(content=\"what is the weather in sf? return this result directly by setting return_direct = True\")]}\n", + "inputs = {\n", + " \"messages\": [\n", + " HumanMessage(\n", + " content=\"what is the weather in sf? return this result directly by setting return_direct = True\"\n", + " )\n", + " ]\n", + "}\n", "for output in app.stream(inputs):\n", " # stream() yields dictionaries with output keyed by node name\n", " for key, value in output.items():\n", diff --git a/examples/chat_agent_executor_with_function_calling/force-calling-a-tool-first.ipynb b/examples/chat_agent_executor_with_function_calling/force-calling-a-tool-first.ipynb index 05096c966..56cca9ce1 100644 --- a/examples/chat_agent_executor_with_function_calling/force-calling-a-tool-first.ipynb +++ b/examples/chat_agent_executor_with_function_calling/force-calling-a-tool-first.ipynb @@ -246,9 +246,10 @@ "import json\n", "from langchain_core.messages import FunctionMessage\n", "\n", + "\n", "# Define the function that determines whether to continue or not\n", "def should_continue(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " last_message = messages[-1]\n", " # If there is no function call, then we finish\n", " if \"function_call\" not in last_message.additional_kwargs:\n", @@ -257,23 +258,27 @@ " else:\n", " return \"continue\"\n", "\n", + "\n", "# Define the function that calls the model\n", "def call_model(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " response = model.invoke(messages)\n", " # We return a list, because this will get added to the existing list\n", " return {\"messages\": [response]}\n", "\n", + "\n", "# Define the function to execute tools\n", "def call_tool(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " # Based on the continue condition\n", " # we know the last message involves a function call\n", " last_message = messages[-1]\n", " # We construct an ToolInvocation from the function_call\n", " action = ToolInvocation(\n", " tool=last_message.additional_kwargs[\"function_call\"][\"name\"],\n", - " tool_input=json.loads(last_message.additional_kwargs[\"function_call\"][\"arguments\"]),\n", + " tool_input=json.loads(\n", + " last_message.additional_kwargs[\"function_call\"][\"arguments\"]\n", + " ),\n", " )\n", " # We call the tool_executor and get back a response\n", " response = tool_executor.invoke(action)\n", @@ -304,20 +309,21 @@ "from langchain_core.messages import AIMessage\n", "import json\n", "\n", + "\n", "def first_model(state):\n", - " human_input = state['messages'][-1].content\n", + " human_input = state[\"messages\"][-1].content\n", " return {\n", " \"messages\": [\n", " AIMessage(\n", - " content=\"\", \n", + " content=\"\",\n", " additional_kwargs={\n", " \"function_call\": {\n", - " \"name\": \"tavily_search_results_json\", \n", - " \"arguments\": json.dumps({\"query\": human_input})\n", - " }\n", + " \"name\": \"tavily_search_results_json\",\n", + " \"arguments\": json.dumps({\"query\": human_input}),\n", " }\n", - " )\n", - " ]\n", + " },\n", + " )\n", + " ]\n", " }" ] }, @@ -343,6 +349,7 @@ "outputs": [], "source": [ "from langgraph.graph import StateGraph, END\n", + "\n", "# Define a new graph\n", "workflow = StateGraph(AgentState)\n", "\n", @@ -374,16 +381,16 @@ " # If `tools`, then we call the tool node.\n", " \"continue\": \"action\",\n", " # Otherwise we finish.\n", - " \"end\": END\n", - " }\n", + " \"end\": END,\n", + " },\n", ")\n", "\n", "# We now add a normal edge from `tools` to `agent`.\n", "# This means that after `tools` is called, `agent` node is called next.\n", - "workflow.add_edge('action', 'agent')\n", + "workflow.add_edge(\"action\", \"agent\")\n", "\n", "# After we call the first agent, we know we want to go to action\n", - "workflow.add_edge('first_agent', 'action')\n", + "workflow.add_edge(\"first_agent\", \"action\")\n", "\n", "# Finally, we compile it!\n", "# This compiles it into a LangChain Runnable,\n", diff --git a/examples/chat_agent_executor_with_function_calling/human-in-the-loop.ipynb b/examples/chat_agent_executor_with_function_calling/human-in-the-loop.ipynb index e2c9d4ac2..91b2af705 100644 --- a/examples/chat_agent_executor_with_function_calling/human-in-the-loop.ipynb +++ b/examples/chat_agent_executor_with_function_calling/human-in-the-loop.ipynb @@ -263,9 +263,10 @@ "import json\n", "from langchain_core.messages import FunctionMessage\n", "\n", + "\n", "# Define the function that determines whether to continue or not\n", "def should_continue(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " last_message = messages[-1]\n", " # If there is no function call, then we finish\n", " if \"function_call\" not in last_message.additional_kwargs:\n", @@ -274,9 +275,10 @@ " else:\n", " return \"continue\"\n", "\n", + "\n", "# Define the function that calls the model\n", "def call_model(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " response = model.invoke(messages)\n", " # We return a list, because this will get added to the existing list\n", " return {\"messages\": [response]}" @@ -301,14 +303,16 @@ "source": [ "# Define the function to execute tools\n", "def call_tool(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " # Based on the continue condition\n", " # we know the last message involves a function call\n", " last_message = messages[-1]\n", " # We construct an ToolInvocation from the function_call\n", " action = ToolInvocation(\n", " tool=last_message.additional_kwargs[\"function_call\"][\"name\"],\n", - " tool_input=json.loads(last_message.additional_kwargs[\"function_call\"][\"arguments\"]),\n", + " tool_input=json.loads(\n", + " last_message.additional_kwargs[\"function_call\"][\"arguments\"]\n", + " ),\n", " )\n", " response = input(f\"[y/n] continue with: {action}?\")\n", " if response == \"n\":\n", @@ -339,6 +343,7 @@ "outputs": [], "source": [ "from langgraph.graph import StateGraph, END\n", + "\n", "# Define a new graph\n", "workflow = StateGraph(AgentState)\n", "\n", @@ -367,13 +372,13 @@ " # If `tools`, then we call the tool node.\n", " \"continue\": \"action\",\n", " # Otherwise we finish.\n", - " \"end\": END\n", - " }\n", + " \"end\": END,\n", + " },\n", ")\n", "\n", "# We now add a normal edge from `tools` to `agent`.\n", "# This means that after `tools` is called, `agent` node is called next.\n", - "workflow.add_edge('action', 'agent')\n", + "workflow.add_edge(\"action\", \"agent\")\n", "\n", "# Finally, we compile it!\n", "# This compiles it into a LangChain Runnable,\n", diff --git a/examples/chat_agent_executor_with_function_calling/managing-agent-steps.ipynb b/examples/chat_agent_executor_with_function_calling/managing-agent-steps.ipynb index c0b7089a3..e21431101 100644 --- a/examples/chat_agent_executor_with_function_calling/managing-agent-steps.ipynb +++ b/examples/chat_agent_executor_with_function_calling/managing-agent-steps.ipynb @@ -246,9 +246,10 @@ "import json\n", "from langchain_core.messages import FunctionMessage\n", "\n", + "\n", "# Define the function that determines whether to continue or not\n", "def should_continue(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " last_message = messages[-1]\n", " # If there is no function call, then we finish\n", " if \"function_call\" not in last_message.additional_kwargs:\n", @@ -277,7 +278,7 @@ "source": [ "# Define the function that calls the model\n", "def call_model(state):\n", - " messages = state['messages'][-5:]\n", + " messages = state[\"messages\"][-5:]\n", " response = model.invoke(messages)\n", " # We return a list, because this will get added to the existing list\n", " return {\"messages\": [response]}" @@ -292,14 +293,16 @@ "source": [ "# Define the function to execute tools\n", "def call_tool(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " # Based on the continue condition\n", " # we know the last message involves a function call\n", " last_message = messages[-1]\n", " # We construct an ToolInvocation from the function_call\n", " action = ToolInvocation(\n", " tool=last_message.additional_kwargs[\"function_call\"][\"name\"],\n", - " tool_input=json.loads(last_message.additional_kwargs[\"function_call\"][\"arguments\"]),\n", + " tool_input=json.loads(\n", + " last_message.additional_kwargs[\"function_call\"][\"arguments\"]\n", + " ),\n", " )\n", " # We call the tool_executor and get back a response\n", " response = tool_executor.invoke(action)\n", @@ -327,6 +330,7 @@ "outputs": [], "source": [ "from langgraph.graph import StateGraph, END\n", + "\n", "# Define a new graph\n", "workflow = StateGraph(AgentState)\n", "\n", @@ -355,13 +359,13 @@ " # If `tools`, then we call the tool node.\n", " \"continue\": \"action\",\n", " # Otherwise we finish.\n", - " \"end\": END\n", - " }\n", + " \"end\": END,\n", + " },\n", ")\n", "\n", "# We now add a normal edge from `tools` to `agent`.\n", "# This means that after `tools` is called, `agent` node is called next.\n", - "workflow.add_edge('action', 'agent')\n", + "workflow.add_edge(\"action\", \"agent\")\n", "\n", "# Finally, we compile it!\n", "# This compiles it into a LangChain Runnable,\n", diff --git a/examples/chat_agent_executor_with_function_calling/respond-in-format.ipynb b/examples/chat_agent_executor_with_function_calling/respond-in-format.ipynb index ea61b18a4..2e64f0fba 100644 --- a/examples/chat_agent_executor_with_function_calling/respond-in-format.ipynb +++ b/examples/chat_agent_executor_with_function_calling/respond-in-format.ipynb @@ -177,8 +177,10 @@ "from langchain_core.pydantic_v1 import BaseModel, Field\n", "from langchain_core.utils.function_calling import convert_pydantic_to_openai_function\n", "\n", + "\n", "class Response(BaseModel):\n", " \"\"\"Final response to the user\"\"\"\n", + "\n", " temperature: float = Field(description=\"the temperature\")\n", " other_notes: str = Field(description=\"any other notes about the weather\")\n", "\n", @@ -264,9 +266,10 @@ "import json\n", "from langchain_core.messages import FunctionMessage\n", "\n", + "\n", "# Define the function that determines whether to continue or not\n", "def should_continue(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " last_message = messages[-1]\n", " # If there is no function call, then we finish\n", " if \"function_call\" not in last_message.additional_kwargs:\n", @@ -278,23 +281,27 @@ " else:\n", " return \"continue\"\n", "\n", + "\n", "# Define the function that calls the model\n", "def call_model(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " response = model.invoke(messages)\n", " # We return a list, because this will get added to the existing list\n", " return {\"messages\": [response]}\n", "\n", + "\n", "# Define the function to execute tools\n", "def call_tool(state):\n", - " messages = state['messages']\n", + " messages = state[\"messages\"]\n", " # Based on the continue condition\n", " # we know the last message involves a function call\n", " last_message = messages[-1]\n", " # We construct an ToolInvocation from the function_call\n", " action = ToolInvocation(\n", " tool=last_message.additional_kwargs[\"function_call\"][\"name\"],\n", - " tool_input=json.loads(last_message.additional_kwargs[\"function_call\"][\"arguments\"]),\n", + " tool_input=json.loads(\n", + " last_message.additional_kwargs[\"function_call\"][\"arguments\"]\n", + " ),\n", " )\n", " # We call the tool_executor and get back a response\n", " response = tool_executor.invoke(action)\n", @@ -322,6 +329,7 @@ "outputs": [], "source": [ "from langgraph.graph import StateGraph, END\n", + "\n", "# Define a new graph\n", "workflow = StateGraph(AgentState)\n", "\n", @@ -350,13 +358,13 @@ " # If `tools`, then we call the tool node.\n", " \"continue\": \"action\",\n", " # Otherwise we finish.\n", - " \"end\": END\n", - " }\n", + " \"end\": END,\n", + " },\n", ")\n", "\n", "# We now add a normal edge from `tools` to `agent`.\n", "# This means that after `tools` is called, `agent` node is called next.\n", - "workflow.add_edge('action', 'agent')\n", + "workflow.add_edge(\"action\", \"agent\")\n", "\n", "# Finally, we compile it!\n", "# This compiles it into a LangChain Runnable,\n", diff --git a/examples/chatbot-simulation-evaluation/agent-simulation-evaluation.ipynb b/examples/chatbot-simulation-evaluation/agent-simulation-evaluation.ipynb index 0510118be..c7ce3b83e 100644 --- a/examples/chatbot-simulation-evaluation/agent-simulation-evaluation.ipynb +++ b/examples/chatbot-simulation-evaluation/agent-simulation-evaluation.ipynb @@ -84,7 +84,10 @@ "\n", "# This is flexible, but you can define your agent here, or call your agent API here.\n", "def my_chat_bot(messages: List[dict]) -> dict:\n", - " system_message = {\"role\": \"system\", \"content\": \"You are a customer support agent for an airline.\"}\n", + " system_message = {\n", + " \"role\": \"system\",\n", + " \"content\": \"You are a customer support agent for an airline.\",\n", + " }\n", " messages = [system_message] + messages\n", " completion = openai.chat.completions.create(\n", " messages=messages, model=\"gpt-3.5-turbo\"\n", @@ -234,8 +237,7 @@ " # Call the chat bot\n", " chat_bot_response = my_chat_bot(messages)\n", " # Respond with an AI Message\n", - " return AIMessage(content=chat_bot_response[\"content\"])\n", - " " + " return AIMessage(content=chat_bot_response[\"content\"])" ] }, { diff --git a/examples/human-in-the-loop.ipynb b/examples/human-in-the-loop.ipynb index 8d97da44e..aaeef496e 100644 --- a/examples/human-in-the-loop.ipynb +++ b/examples/human-in-the-loop.ipynb @@ -233,6 +233,7 @@ "import json\n", "from langchain_core.messages import FunctionMessage\n", "\n", + "\n", "# Define the function that determines whether to continue or not\n", "def should_continue(messages):\n", " last_message = messages[-1]\n", @@ -243,12 +244,14 @@ " else:\n", " return \"continue\"\n", "\n", + "\n", "# Define the function that calls the model\n", "def call_model(messages):\n", " response = model.invoke(messages)\n", " # We return a list, because this will get added to the existing list\n", " return response\n", "\n", + "\n", "# Define the function to execute tools\n", "def call_tool(messages):\n", " # Based on the continue condition\n", @@ -257,7 +260,9 @@ " # We construct an ToolInvocation from the function_call\n", " action = ToolInvocation(\n", " tool=last_message.additional_kwargs[\"function_call\"][\"name\"],\n", - " tool_input=json.loads(last_message.additional_kwargs[\"function_call\"][\"arguments\"]),\n", + " tool_input=json.loads(\n", + " last_message.additional_kwargs[\"function_call\"][\"arguments\"]\n", + " ),\n", " )\n", " # We call the tool_executor and get back a response\n", " response = tool_executor.invoke(action)\n", @@ -285,6 +290,7 @@ "outputs": [], "source": [ "from langgraph.graph import MessageGraph, END\n", + "\n", "# Define a new graph\n", "workflow = MessageGraph()\n", "\n", @@ -313,13 +319,13 @@ " # If `tools`, then we call the tool node.\n", " \"continue\": \"action\",\n", " # Otherwise we finish.\n", - " \"end\": END\n", - " }\n", + " \"end\": END,\n", + " },\n", ")\n", "\n", "# We now add a normal edge from `tools` to `agent`.\n", "# This means that after `tools` is called, `agent` node is called next.\n", - "workflow.add_edge('action', 'agent')" + "workflow.add_edge(\"action\", \"agent\")" ] }, { @@ -364,7 +370,7 @@ "# Finally, we compile it!\n", "# This compiles it into a LangChain Runnable,\n", "# meaning you can use it as you would any other runnable\n", - "app = workflow.compile(checkpointer=memory, interrupt_before=['action'])" + "app = workflow.compile(checkpointer=memory, interrupt_before=[\"action\"])" ] }, { @@ -393,6 +399,7 @@ ], "source": [ "from langchain_core.messages import HumanMessage\n", + "\n", "inputs = [HumanMessage(content=\"hi! I'm bob\")]\n", "for event in app.stream(inputs, {\"configurable\": {\"thread_id\": \"2\"}}):\n", " for k, v in event.items():\n", diff --git a/examples/persistence.ipynb b/examples/persistence.ipynb index 98edfb1b0..9272e5079 100644 --- a/examples/persistence.ipynb +++ b/examples/persistence.ipynb @@ -227,6 +227,7 @@ "import json\n", "from langchain_core.messages import FunctionMessage\n", "\n", + "\n", "# Define the function that determines whether to continue or not\n", "def should_continue(messages):\n", " last_message = messages[-1]\n", @@ -237,12 +238,14 @@ " else:\n", " return \"continue\"\n", "\n", + "\n", "# Define the function that calls the model\n", "def call_model(messages):\n", " response = model.invoke(messages)\n", " # We return a list, because this will get added to the existing list\n", " return response\n", "\n", + "\n", "# Define the function to execute tools\n", "def call_tool(messages):\n", " # Based on the continue condition\n", @@ -251,7 +254,9 @@ " # We construct an ToolInvocation from the function_call\n", " action = ToolInvocation(\n", " tool=last_message.additional_kwargs[\"function_call\"][\"name\"],\n", - " tool_input=json.loads(last_message.additional_kwargs[\"function_call\"][\"arguments\"]),\n", + " tool_input=json.loads(\n", + " last_message.additional_kwargs[\"function_call\"][\"arguments\"]\n", + " ),\n", " )\n", " # We call the tool_executor and get back a response\n", " response = tool_executor.invoke(action)\n", @@ -279,6 +284,7 @@ "outputs": [], "source": [ "from langgraph.graph import MessageGraph, END\n", + "\n", "# Define a new graph\n", "workflow = MessageGraph()\n", "\n", @@ -307,13 +313,13 @@ " # If `tools`, then we call the tool node.\n", " \"continue\": \"action\",\n", " # Otherwise we finish.\n", - " \"end\": END\n", - " }\n", + " \"end\": END,\n", + " },\n", ")\n", "\n", "# We now add a normal edge from `tools` to `agent`.\n", "# This means that after `tools` is called, `agent` node is called next.\n", - "workflow.add_edge('action', 'agent')" + "workflow.add_edge(\"action\", \"agent\")" ] }, { @@ -377,6 +383,7 @@ ], "source": [ "from langchain_core.messages import HumanMessage\n", + "\n", "inputs = [HumanMessage(content=\"hi! I'm bob\")]\n", "for event in app.stream(inputs, {\"configurable\": {\"thread_id\": \"2\"}}):\n", " for k, v in event.items():\n", diff --git a/examples/rag/langgraph_crag.ipynb b/examples/rag/langgraph_crag.ipynb index a058d2aa8..a9f583384 100644 --- a/examples/rag/langgraph_crag.ipynb +++ b/examples/rag/langgraph_crag.ipynb @@ -514,7 +514,7 @@ " pprint.pprint(\"\\n---\\n\")\n", "\n", "# Final generation\n", - "pprint.pprint(value['keys']['generation'])" + "pprint.pprint(value[\"keys\"][\"generation\"])" ] }, { @@ -560,17 +560,21 @@ ], "source": [ "# Correction for question not present in context\n", - "inputs = {\"keys\": {\"question\": \"What is the approach for code generation taken in the AlphaCodium paper?\"}}\n", + "inputs = {\n", + " \"keys\": {\n", + " \"question\": \"What is the approach for code generation taken in the AlphaCodium paper?\"\n", + " }\n", + "}\n", "for output in app.stream(inputs):\n", " for key, value in output.items():\n", " # Node\n", " pprint.pprint(f\"Node '{key}':\")\n", - " # Optional: print full state \n", + " # Optional: print full state\n", " # pprint.pprint(value[\"keys\"], indent=2, width=80, depth=None)\n", " pprint.pprint(\"\\n---\\n\")\n", "\n", "# Final generation\n", - "pprint.pprint(value['keys']['generation'])" + "pprint.pprint(value[\"keys\"][\"generation\"])" ] }, { diff --git a/examples/rag/langgraph_crag_mistral.ipynb b/examples/rag/langgraph_crag_mistral.ipynb index 5c84f59ab..36c6099c1 100644 --- a/examples/rag/langgraph_crag_mistral.ipynb +++ b/examples/rag/langgraph_crag_mistral.ipynb @@ -339,7 +339,7 @@ " It does not need to be a stringent test. The goal is to filter out erroneous retrievals. \\n\n", " Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question. \\n\n", " Provide the binary score as a JSON with a single key 'score' and no premable or explaination.\"\"\",\n", - " input_variables=[\"question\",\"context\"],\n", + " input_variables=[\"question\", \"context\"],\n", " )\n", "\n", " chain = prompt | llm | JsonOutputParser()\n", @@ -598,7 +598,7 @@ " pprint.pprint(\"\\n---\\n\")\n", "\n", "# Final generation\n", - "pprint.pprint(value['keys']['generation'])" + "pprint.pprint(value[\"keys\"][\"generation\"])" ] }, { @@ -684,7 +684,7 @@ " pprint.pprint(\"\\n---\\n\")\n", "\n", "# Final generation\n", - "pprint.pprint(value['keys']['generation'])" + "pprint.pprint(value[\"keys\"][\"generation\"])" ] }, { diff --git a/examples/rag/langgraph_self_rag.ipynb b/examples/rag/langgraph_self_rag.ipynb index b4b1766f3..cf1fc7ed4 100644 --- a/examples/rag/langgraph_self_rag.ipynb +++ b/examples/rag/langgraph_self_rag.ipynb @@ -659,7 +659,7 @@ " pprint.pprint(\"\\n---\\n\")\n", "\n", "# Final generation\n", - "pprint.pprint(value['keys']['generation'])" + "pprint.pprint(value[\"keys\"][\"generation\"])" ] }, { @@ -717,7 +717,7 @@ " pprint.pprint(\"\\n---\\n\")\n", "\n", "# Final generation\n", - "pprint.pprint(value['keys']['generation'])" + "pprint.pprint(value[\"keys\"][\"generation\"])" ] }, { diff --git a/examples/self-discover/self-discover.ipynb b/examples/self-discover/self-discover.ipynb index fa337d58a..3c5f44b2c 100644 --- a/examples/self-discover/self-discover.ipynb +++ b/examples/self-discover/self-discover.ipynb @@ -278,7 +278,7 @@ "source": [ "def select(inputs):\n", " select_chain = select_prompt | model | StrOutputParser()\n", - " return {\"selected_modules\": select_chain.invoke(inputs)}\n" + " return {\"selected_modules\": select_chain.invoke(inputs)}" ] }, { @@ -358,7 +358,7 @@ "reasoning_modules = [\n", " \"1. How could I devise an experiment to help solve that problem?\",\n", " \"2. Make a list of ideas for solving this problem, and apply them one by one to the problem to see if any progress can be made.\",\n", - " #\"3. How could I measure progress on this problem?\",\n", + " # \"3. How could I measure progress on this problem?\",\n", " \"4. How can I simplify the problem so that it is easier to solve?\",\n", " \"5. What are the key assumptions underlying this problem?\",\n", " \"6. What are the potential risks and drawbacks of each solution?\",\n", @@ -367,10 +367,10 @@ " \"9. How can I break down this problem into smaller, more manageable parts?\",\n", " \"10. Critical Thinking: This style involves analyzing the problem from different perspectives, questioning assumptions, and evaluating the evidence or information available. It focuses on logical reasoning, evidence-based decision-making, and identifying potential biases or flaws in thinking.\",\n", " \"11. Try creative thinking, generate innovative and out-of-the-box ideas to solve the problem. Explore unconventional solutions, thinking beyond traditional boundaries, and encouraging imagination and originality.\",\n", - " #\"12. Seek input and collaboration from others to solve the problem. Emphasize teamwork, open communication, and leveraging the diverse perspectives and expertise of a group to come up with effective solutions.\",\n", + " # \"12. Seek input and collaboration from others to solve the problem. Emphasize teamwork, open communication, and leveraging the diverse perspectives and expertise of a group to come up with effective solutions.\",\n", " \"13. Use systems thinking: Consider the problem as part of a larger system and understanding the interconnectedness of various elements. Focuses on identifying the underlying causes, feedback loops, and interdependencies that influence the problem, and developing holistic solutions that address the system as a whole.\",\n", " \"14. Use Risk Analysis: Evaluate potential risks, uncertainties, and tradeoffs associated with different solutions or approaches to a problem. Emphasize assessing the potential consequences and likelihood of success or failure, and making informed decisions based on a balanced analysis of risks and benefits.\",\n", - " #\"15. Use Reflective Thinking: Step back from the problem, take the time for introspection and self-reflection. Examine personal biases, assumptions, and mental models that may influence problem-solving, and being open to learning from past experiences to improve future approaches.\",\n", + " # \"15. Use Reflective Thinking: Step back from the problem, take the time for introspection and self-reflection. Examine personal biases, assumptions, and mental models that may influence problem-solving, and being open to learning from past experiences to improve future approaches.\",\n", " \"16. What is the core issue or problem that needs to be addressed?\",\n", " \"17. What are the underlying causes or factors contributing to the problem?\",\n", " \"18. Are there any potential solutions or strategies that have been tried before? If yes, what were the outcomes and lessons learned?\",\n", @@ -393,8 +393,8 @@ " \"35. Let’s imagine the current best solution is totally wrong, what other ways are there to think about the problem specification?\"\n", " \"36. What is the best way to modify this current best solution, given what you know about these kinds of problem specification?\"\n", " \"37. Ignoring the current best solution, create an entirely new solution to the problem.\"\n", - " #\"38. Let’s think step by step.\"\n", - " \"39. Let’s make a step by step plan and implement it with good notation and explanation.\"\n", + " # \"38. Let’s think step by step.\"\n", + " \"39. Let’s make a step by step plan and implement it with good notation and explanation.\",\n", "]\n", "\n", "\n", @@ -434,7 +434,9 @@ } ], "source": [ - "for s in app.stream({\"task_description\": task_example, \"reasoning_modules\": reasoning_modules_str}):\n", + "for s in app.stream(\n", + " {\"task_description\": task_example, \"reasoning_modules\": reasoning_modules_str}\n", + "):\n", " print(s)" ] }, diff --git a/examples/streaming-tokens.ipynb b/examples/streaming-tokens.ipynb index 3b19a50e3..8231182b2 100644 --- a/examples/streaming-tokens.ipynb +++ b/examples/streaming-tokens.ipynb @@ -240,6 +240,7 @@ "import json\n", "from langchain_core.messages import FunctionMessage\n", "\n", + "\n", "# Define the function that determines whether to continue or not\n", "def should_continue(messages):\n", " last_message = messages[-1]\n", @@ -250,12 +251,14 @@ " else:\n", " return \"continue\"\n", "\n", + "\n", "# Define the function that calls the model\n", "async def call_model(messages):\n", " response = await model.ainvoke(messages)\n", " # We return a list, because this will get added to the existing list\n", " return response\n", "\n", + "\n", "# Define the function to execute tools\n", "async def call_tool(messages):\n", " # Based on the continue condition\n", @@ -264,7 +267,9 @@ " # We construct an ToolInvocation from the function_call\n", " action = ToolInvocation(\n", " tool=last_message.additional_kwargs[\"function_call\"][\"name\"],\n", - " tool_input=json.loads(last_message.additional_kwargs[\"function_call\"][\"arguments\"]),\n", + " tool_input=json.loads(\n", + " last_message.additional_kwargs[\"function_call\"][\"arguments\"]\n", + " ),\n", " )\n", " # We call the tool_executor and get back a response\n", " response = await tool_executor.ainvoke(action)\n", @@ -292,6 +297,7 @@ "outputs": [], "source": [ "from langgraph.graph import MessageGraph, END\n", + "\n", "# Define a new graph\n", "workflow = MessageGraph()\n", "\n", @@ -320,13 +326,13 @@ " # If `tools`, then we call the tool node.\n", " \"continue\": \"action\",\n", " # Otherwise we finish.\n", - " \"end\": END\n", - " }\n", + " \"end\": END,\n", + " },\n", ")\n", "\n", "# We now add a normal edge from `tools` to `agent`.\n", "# This means that after `tools` is called, `agent` node is called next.\n", - "workflow.add_edge('action', 'agent')\n", + "workflow.add_edge(\"action\", \"agent\")\n", "\n", "# Finally, we compile it!\n", "# This compiles it into a LangChain Runnable,\n", @@ -375,6 +381,7 @@ ], "source": [ "from langchain_core.messages import HumanMessage\n", + "\n", "inputs = [HumanMessage(content=\"what is the weather in sf\")]\n", "async for event in app.astream_events(inputs, version=\"v1\"):\n", " kind = event[\"event\"]\n",