from dotenv import load_dotenv load_dotenv() # take environment variables from .env.
from typing import Annotated, Literal from langchain_community.tools.tavily_search import TavilySearchResults from langchain_core.tools import tool from langchain_experimental.utilities import PythonREPL from langchain_core.messages import BaseMessage, HumanMessage from langchain_openai import ChatOpenAI from langgraph.prebuilt import create_react_agent from langgraph.graph import MessagesState, END from langgraph.types import Command from langgraph.graph import StateGraph, START
@tool defpython_repl_tool( code: Annotated[str, "The python code to execute to generate your chart."], ): """执行 Python 代码""" try: result = repl.run(code) except BaseException as e: returnf"Failed to execute. Error: {repr(e)}" result_str = f"Successfully executed:\n\`\`\`python\n{code}\n\`\`\`\nStdout: {result}" return ( result_str + "\n\nIf you have completed all tasks, respond with FINAL ANSWER." )
defmake_system_prompt(suffix: str) -> str: return ( "You are a helpful AI assistant, collaborating with other assistants to solve a task." "IMPORTANT: If you have the final answer or deliverable, response with 'FINAL ANSWER'." f"\n{suffix}" )
chart_agent = create_react_agent( llm, tools=[python_repl_tool], state_modifier=make_system_prompt( "Generate and Run the python code to display the chart" "Matplotlib code should add: import matplotlib;matplotlib.use('Agg'), in the first line." "File should save to current directory." ), )
for step in graph.stream( { "messages": [ ( "user", "First, search the China's GDP over the past 5 years, then make a line chart of it. " "Once you make the chart, finish.", ) ], }, {"recursion_limit": 10}, ): print(step) print('-' * 20)