mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-09-10 03:37:51 +02:00
Reflexion
This commit is contained in:
@@ -0,0 +1,533 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "22942f7e-3446-4009-b551-cca7fcc25d73",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Reflexion\n",
|
||||
"\n",
|
||||
"[Reflexion](https://arxiv.org/abs/2303.11366) by Shinn, et. al., is an architecture designed to learn through verbal feedback by means of an episodic memory unit.\n",
|
||||
"\n",
|
||||
"It's got 3 main components:\n",
|
||||
"1. Actor with Self-reflection\n",
|
||||
"2. Evaluator\n",
|
||||
"4. Memory\n",
|
||||
"\n",
|
||||
"Below, we implement in LangGraph."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "906edf48-7c81-48b8-8250-fdc34043d01b",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## 0. Prerequisites"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "1b64a6f6-1d32-48be-92b5-66c3b04b17f7",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# %pip install -U langchain langgraph langchain_openai"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"id": "a917bb70-f84c-48e6-8d32-d14f9df2ca2f",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import getpass\n",
|
||||
"import os\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def _set_if_undefined(var: str) -> None:\n",
|
||||
" if os.environ.get(var):\n",
|
||||
" return\n",
|
||||
" os.environ[var] = getpass.getpass(var)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"# Optional: Configure tracing to visualize and debug the agent\n",
|
||||
"_set_if_undefined(\"LANGCHAIN_API_KEY\")\n",
|
||||
"os.environ[\"LANGCHAIN_TRACING_V2\"] = \"true\"\n",
|
||||
"os.environ[\"LANGCHAIN_PROJECT\"] = \"Reflexion\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "a6f1c62c-3441-4945-b482-7307e2c8778a",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"We will use tavily search as a tool. You can get an API key [here](https://app.tavily.com/sign-in) or replace with a different tool of your choosing."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"id": "0757d536-dc29-44f0-8c3d-2ffeaad67a25",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# %pip install tavily-python"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"id": "bc6cd673-ef9b-4854-9561-88fa59f9eb88",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"_set_if_undefined(\"OPENAI_API_KEY\")\n",
|
||||
"_set_if_undefined(\"TAVILY_API_KEY\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "af543598-52d0-4ec3-a05f-d2954ff793ee",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Actor"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"id": "5a2ac853-b8a6-40de-b7fe-3f9f3c5ca4d2",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from langchain.tools.tavily_search import TavilySearchResults\n",
|
||||
"from langchain.utilities.tavily_search import TavilySearchAPIWrapper\n",
|
||||
"\n",
|
||||
"search = TavilySearchAPIWrapper()\n",
|
||||
"tavily_tool = TavilySearchResults(api_wrapper=search, max_results=5)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 8,
|
||||
"id": "5fffa8d5-068a-4f0b-adfc-b4daf30ef294",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import datetime\n",
|
||||
"from typing import List\n",
|
||||
"\n",
|
||||
"from langchain.chains import create_structured_output_runnable\n",
|
||||
"from langchain.output_parsers.openai_tools import JsonOutputToolsParser\n",
|
||||
"from langchain.prompts.chat import ChatPromptTemplate, MessagesPlaceholder\n",
|
||||
"from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, ToolMessage\n",
|
||||
"from langchain_core.pydantic_v1 import BaseModel, Field\n",
|
||||
"from langchain_openai import ChatOpenAI\n",
|
||||
"\n",
|
||||
"actor_prompt_template = ChatPromptTemplate.from_messages(\n",
|
||||
" [\n",
|
||||
" (\n",
|
||||
" \"system\",\n",
|
||||
" \"\"\"You are expert researcher.\n",
|
||||
"Current time: {time}\n",
|
||||
"\n",
|
||||
"1. {first_instruction}\n",
|
||||
"2. Reflect and critique your answer. Be severe to maximize improvement.\n",
|
||||
"3. Recommend a search query to research information and improve your answer.\"\"\",\n",
|
||||
" ),\n",
|
||||
" MessagesPlaceholder(variable_name=\"messages\"),\n",
|
||||
" (\"system\", \"Answer the user's question above using the required format.\"),\n",
|
||||
" ]\n",
|
||||
").partial(\n",
|
||||
" time=lambda: datetime.datetime.now().isoformat(),\n",
|
||||
")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"class Reflection(BaseModel):\n",
|
||||
" missing: str = Field(description=\"Critique of what is missing.\")\n",
|
||||
" superfluous: str = Field(description=\"Critique of what is superfluous\")\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"class AnswerQuestion(BaseModel):\n",
|
||||
" \"\"\"Answer the question.\"\"\"\n",
|
||||
"\n",
|
||||
" answer: str = Field(description=\"~250 word detailed answer to the question.\")\n",
|
||||
" reflection: Reflection = Field(description=\"Your reflection on the initial answer.\")\n",
|
||||
" search_queries: List[str] = Field(\n",
|
||||
" description=\"1-3 search queries for researching improvements to address the critique of your current answer.\"\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def nest(state: List[BaseMessage]):\n",
|
||||
" return {\"messages\": state}\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"llm = ChatOpenAI(model=\"gpt-4-turbo-preview\")\n",
|
||||
"initial_answer_chain = (\n",
|
||||
" nest\n",
|
||||
" | actor_prompt_template.partial(\n",
|
||||
" first_instruction=\"Provide a detailed ~250 word answer.\"\n",
|
||||
" )\n",
|
||||
" | llm.bind_tools(tools=[AnswerQuestion], tool_choice=\"AnswerQuestion\")\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 9,
|
||||
"id": "5922e1fe-7533-4f41-8b1d-d812707c1968",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"initial = initial_answer_chain.invoke(\n",
|
||||
" [HumanMessage(content=\"Why the US should NOT adopt rank-choice voting\")]\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 10,
|
||||
"id": "cbcfde28-626a-47c4-88db-3d8ae45f0100",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"{'type': 'AnswerQuestion',\n",
|
||||
" 'args': {'answer': 'The debate around whether the United States should adopt ranked-choice voting (RCV) is complex, involving various considerations spanning democratic principles, electoral outcomes, and practical implications. Opponents of RCV argue against its adoption in the US for several reasons. Firstly, RCV can be more complicated for voters to understand and participate in compared to the traditional plurality voting system. This complexity might discourage voter participation or lead to a higher rate of ballot errors, ultimately undermining the democratic process. Secondly, while RCV is designed to produce a consensus candidate that reflects a broader preference among the electorate, critics argue that it can lead to moderate, less polarizing candidates being elected, potentially stifling vibrant political debate and reducing the diversity of political thought represented in government. Thirdly, the implementation of RCV would require significant changes to the existing electoral infrastructure, including updates to voting machines and the training of election officials, which could be costly and time-consuming. There are also concerns about the potential for increased confusion during the transition period, which could affect election integrity. Lastly, some detractors contend that RCV does not necessarily solve the problem of strategic voting, as voters may still attempt to game the system by ranking candidates in a way that does not reflect their true preferences, merely to avoid the election of their least preferred candidate.',\n",
|
||||
" 'reflection': {'missing': 'Specific examples or studies that support the arguments against RCV, such as instances where RCV led to voter confusion or did not eliminate strategic voting.',\n",
|
||||
" 'superfluous': 'The answer might have spent too much time explaining the general concept of RCV before diving into the specific reasons against its adoption in the US, which could have been briefly summarized to allow more space for detailed criticisms.'},\n",
|
||||
" 'search_queries': ['ranked-choice voting disadvantages studies',\n",
|
||||
" 'RCV implementation costs and challenges',\n",
|
||||
" 'Effects of RCV on voter participation and strategic voting']},\n",
|
||||
" 'id': 'call_dg5IemqOS5EfSJCJY88rQMrm'}"
|
||||
]
|
||||
},
|
||||
"execution_count": 10,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"parser = JsonOutputToolsParser(return_id=True)\n",
|
||||
"parsed = parser.invoke(initial)\n",
|
||||
"parsed[0]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "c4c7af31-b469-46fc-b441-0acb28515c7a",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"#### Actor pt 2: Revise"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 11,
|
||||
"id": "2605fd8d-c663-446f-ba25-751190195749",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"revise_instructions = \"\"\"Revise your previous answer using the new information.\n",
|
||||
" - You should use the previous critique to add important information to your answer.\n",
|
||||
" - You MUST include numerical citations in your revised answer to ensure it can be verified.\n",
|
||||
" - Add a \"References\" section to the bottom of your answer (which does not count towards the word limit). In form of:\n",
|
||||
" - [1] https://example.com\n",
|
||||
" - [2] https://example.com\n",
|
||||
" - You should use the previous critique to remove superfluous information from your answer and make SURE it is not more than 250 words.\n",
|
||||
"\"\"\"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"class ReviseAnswer(AnswerQuestion):\n",
|
||||
" \"\"\"Revise your original answer to your question.\"\"\"\n",
|
||||
"\n",
|
||||
" references: List[str] = Field(\n",
|
||||
" description=\"Citations motivating your updated answer.\"\n",
|
||||
" )\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"revision_chain = (\n",
|
||||
" nest\n",
|
||||
" | actor_prompt_template.partial(first_instruction=revise_instructions)\n",
|
||||
" | llm.bind_tools(tools=[ReviseAnswer], tool_choice=\"ReviseAnswer\")\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 15,
|
||||
"id": "c55e8e2d-c9e3-4245-b2b2-c41f624d7574",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"['ranked-choice voting disadvantages studies',\n",
|
||||
" 'RCV implementation costs and challenges',\n",
|
||||
" 'Effects of RCV on voter participation and strategic voting']"
|
||||
]
|
||||
},
|
||||
"execution_count": 15,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"parsed[0][\"args\"][\"search_queries\"]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 16,
|
||||
"id": "6fd51f17-c0b0-44b6-90e2-55a66cb8f5a7",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import json\n",
|
||||
"\n",
|
||||
"revised = revision_chain.invoke(\n",
|
||||
" [\n",
|
||||
" HumanMessage(content=\"Why the US should NOT adopt rank-choice voting\"),\n",
|
||||
" initial,\n",
|
||||
" ToolMessage(\n",
|
||||
" tool_call_id=initial.additional_kwargs[\"tool_calls\"][0][\"id\"],\n",
|
||||
" content=json.dumps(\n",
|
||||
" tavily_tool.invoke(str(parsed[0][\"args\"][\"search_queries\"]))\n",
|
||||
" ),\n",
|
||||
" ),\n",
|
||||
" ]\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 17,
|
||||
"id": "28685e81-5461-47fe-bebd-2af6e552761b",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"[{'type': 'ReviseAnswer',\n",
|
||||
" 'args': {'answer': 'Opponents of ranked-choice voting (RCV) in the United States highlight several key concerns against its adoption. First, RCV can introduce complexity and confusion for voters, potentially leading to increased ballot errors and decreased voter participation[1]. This complexity may undermine the democratic process by discouraging engagement. Second, the transition to RCV would entail considerable costs and logistical challenges, including updating voting machines and training election officials. The need for significant changes to electoral infrastructure could pose financial and operational burdens[2]. Third, critics argue RCV might not eliminate strategic voting, as voters could still rank candidates in a non-genuine manner to influence the election outcome[3]. Moreover, while RCV aims to elect consensus candidates, this can result in the election of moderate, less polarizing figures, potentially dampening political diversity and debate[4]. Lastly, the implementation of RCV could lead to initial confusion and concerns over election integrity during the transition, impacting public trust in the electoral process[5]. These factors combined suggest that the adoption of RCV in the U.S. might not yield the intended democratic enhancements and could introduce new challenges to the electoral system.\\n\\nReferences:\\n[1] https://thefga.org/research/ranked-choice-voting-a-disaster-in-disguise/\\n[2] https://www.npr.org/2023/12/13/1214199019/ranked-choice-voting-explainer\\n[3] https://www.csg.org/2023/03/21/ranked-choice-voting-what-where-why-why-not/\\n[4] https://cs50.harvard.edu/college/2024/spring/psets/3/runoff/\\n[5] https://www.nytimes.com/2024/02/08/us/ranked-choice-voting-elections.html',\n",
|
||||
" 'reflection': {'missing': 'Precise data or studies that quantify the impact of RCV on voter participation, ballot errors, and strategic voting.',\n",
|
||||
" 'superfluous': 'The initial answer lacked direct references and included broad, unsubstantiated claims. The revised version focuses on specific criticisms and removes general explanations of RCV that do not directly address the question.',\n",
|
||||
" 'search_queries': ['ranked-choice voting impact on voter turnout',\n",
|
||||
" 'RCV ballot error rate study',\n",
|
||||
" 'strategic voting in RCV elections'],\n",
|
||||
" 'references': ['https://thefga.org/research/ranked-choice-voting-a-disaster-in-disguise/',\n",
|
||||
" 'https://www.npr.org/2023/12/13/1214199019/ranked-choice-voting-explainer',\n",
|
||||
" 'https://www.csg.org/2023/03/21/ranked-choice-voting-what-where-why-why-not/',\n",
|
||||
" 'https://cs50.harvard.edu/college/2024/spring/psets/3/runoff/',\n",
|
||||
" 'https://www.nytimes.com/2024/02/08/us/ranked-choice-voting-elections.html']}},\n",
|
||||
" 'id': 'call_2HQBy80sY704ENtB6IvgRhZl'}]"
|
||||
]
|
||||
},
|
||||
"execution_count": 17,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"parsed = parser.invoke(revised)\n",
|
||||
"parsed"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "a9464ee2-58eb-4a01-ae71-fa72a0314910",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Graph"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 57,
|
||||
"id": "5376f182-d42a-43d8-bfd4-d53dc1ae9013",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from collections import defaultdict\n",
|
||||
"\n",
|
||||
"from langgraph.prebuilt.tool_executor import ToolExecutor, ToolInvocation\n",
|
||||
"\n",
|
||||
"# This a helper class we have that is useful for running tools\n",
|
||||
"# It takes in an agent action and calls that tool and returns the result\n",
|
||||
"tool_executor = ToolExecutor([tavily_tool])\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def execute_tools(state: List[BaseMessage]) -> List[BaseMessage]:\n",
|
||||
" tool_invocation: AIMessage = state[-1]\n",
|
||||
" parsed_tool_calls = parser.invoke(tool_invocation)\n",
|
||||
" ids = []\n",
|
||||
" tool_invocations = []\n",
|
||||
" for parsed_call in parsed_tool_calls:\n",
|
||||
" for query in parsed_call[\"args\"][\"search_queries\"]:\n",
|
||||
" tool_invocations.append(\n",
|
||||
" ToolInvocation(\n",
|
||||
" # We only have this one for now. Would want to map it\n",
|
||||
" # if we change\n",
|
||||
" tool=\"tavily_search_results_json\",\n",
|
||||
" tool_input=query,\n",
|
||||
" )\n",
|
||||
" )\n",
|
||||
" ids.append(parsed_call[\"id\"])\n",
|
||||
"\n",
|
||||
" outputs = tool_executor.batch(tool_invocations)\n",
|
||||
" outputs_map = defaultdict(dict)\n",
|
||||
" for id_, output, invocation in zip(ids, outputs, tool_invocations):\n",
|
||||
" outputs_map[id_][invocation.tool_input] = output\n",
|
||||
"\n",
|
||||
" return [\n",
|
||||
" ToolMessage(content=json.dumps(query_outputs), tool_call_id=id_)\n",
|
||||
" for id_, query_outputs in outputs_map.items()\n",
|
||||
" ]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 58,
|
||||
"id": "02120f42-099d-41d8-8278-4d52df0e3147",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"MAX_ITERATIONS = 5\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def _get_num_iterations(state: List[BaseMessage]):\n",
|
||||
" i = 0\n",
|
||||
" for m in state[::-1]:\n",
|
||||
" if not isinstance(m, (ToolMessage, AIMessage)):\n",
|
||||
" break\n",
|
||||
" i += 1\n",
|
||||
" return i\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def event_loop(state: List[BaseMessage]) -> str:\n",
|
||||
" num_iterations = _get_num_iterations(state)\n",
|
||||
" if num_iterations > MAX_ITERATIONS:\n",
|
||||
" return END\n",
|
||||
" return \"execute_tools\""
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 59,
|
||||
"id": "3c57318f-a30c-4dbd-9b88-f2633e8cb3b1",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from langgraph.graph import END, MessageGraph\n",
|
||||
"\n",
|
||||
"builder = MessageGraph()\n",
|
||||
"builder.add_node(\"draft\", initial_answer_chain)\n",
|
||||
"builder.add_node(\"execute_tools\", execute_tools)\n",
|
||||
"builder.add_node(\"revise\", revision_chain)\n",
|
||||
"builder.add_edge(\"draft\", \"execute_tools\")\n",
|
||||
"builder.add_edge(\"execute_tools\", \"revise\")\n",
|
||||
"builder.add_conditional_edges(\"revise\", event_loop)\n",
|
||||
"builder.set_entry_point(\"draft\")\n",
|
||||
"graph = builder.compile()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 61,
|
||||
"id": "2634a3ea-7423-4579-9f4e-390e439c3209",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"## 1. draft\n",
|
||||
"content='' additional_kwargs={'tool_calls': [{'id': 'call_umpIUt5pLhCGImf8XCcMiZlD', 'function': {'a ...\n",
|
||||
"---\n",
|
||||
"## 2. execute_tools\n",
|
||||
"[ToolMessage(content='{\"successful climate change mitigation examples\": [{\"url\": \"https://www.washin ...\n",
|
||||
"---\n",
|
||||
"## 3. revise\n",
|
||||
"content='' additional_kwargs={'tool_calls': [{'id': 'call_rutKnOqvPZoG5sSS6Be46RUn', 'function': {'a ...\n",
|
||||
"---\n",
|
||||
"## 4. execute_tools\n",
|
||||
"[ToolMessage(content='{\"climate crisis innovative policy examples\": [{\"url\": \"https://www.forbes.com ...\n",
|
||||
"---\n",
|
||||
"## 5. revise\n",
|
||||
"content='' additional_kwargs={'tool_calls': [{'id': 'call_kUUMiW7z7IDbsMOlD25zI221', 'function': {'a ...\n",
|
||||
"---\n",
|
||||
"## 6. execute_tools\n",
|
||||
"[ToolMessage(content='{\"climate crisis innovative policy examples\": [{\"url\": \"https://www.worldwildl ...\n",
|
||||
"---\n",
|
||||
"## 7. revise\n",
|
||||
"content='' additional_kwargs={'tool_calls': [{'id': 'call_EY7kiUhu6h3jemW0HrEfo2aP', 'function': {'a ...\n",
|
||||
"---\n",
|
||||
"## 8. __end__\n",
|
||||
"[HumanMessage(content='How should we handle the climate crisis?'), AIMessage(content='', additional_ ...\n",
|
||||
"---\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"events = graph.stream(\n",
|
||||
" [HumanMessage(content=\"How should we handle the climate crisis?\")]\n",
|
||||
")\n",
|
||||
"for i, step in enumerate(events):\n",
|
||||
" node, output = next(iter(step.items()))\n",
|
||||
" print(f\"## {i+1}. {node}\")\n",
|
||||
" print(str(output)[:100] + \" ...\")\n",
|
||||
" print(\"---\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "c9195436-aed9-4356-948b-2ca081a6d0bf",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(step[END])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "13ab420d-c16d-4274-a694-491ccf94dc74",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Memory"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "471dae8b-7385-4185-a07a-eb9d28090d5a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3 (ipykernel)",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.2"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
Reference in New Issue
Block a user