langgraph 多智能体 Multi-agent supervisor

news2024/12/27 7:49:12

1. 工具定义

1.1网络搜索工具

from typing import Annotated
import os
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.tools import tool
from langchain_experimental.utilities import PythonREPL

os.environ["TAVILY_API_KEY"] = "your api key"
tavily_tool = TavilySearchResults(max_results=3)

1.2 代码执行工具

from autogen_core.base import CancellationToken
from autogen_core.components.tools import PythonCodeExecutionTool
from autogen_ext.code_executors import DockerCommandLineCodeExecutor

# Create the tool.
code_executor = DockerCommandLineCodeExecutor()
await code_executor.start()
code_execution_tool = PythonCodeExecutionTool(code_executor)
cancellation_token = CancellationToken()


from langgraph.prebuilt import ToolNode


@tool
async def code_executor(
    code: Annotated[str, "The python code to execute."],                        
):
    """Use this to execute python code. If you want to see the output of a value,
    you should print it out with `print(...)`. This is visible to the user."""
    
    try:
        result = await code_execution_tool.run_json({"code": code}, cancellation_token)
    except BaseException as e:
        return f"Failed to execute. Error: {repr(e)}"
    
    
    result= code_execution_tool.return_value_as_string(result)
    
    result_str = f"The result is:{result}"
    return result_str

2. graph中各节点定义

from langgraph.graph import MessagesState

# The agent state is the input to each node in the graph
class AgentState(MessagesState):
    # The 'next' field indicates where to route to next
    next: str

from typing import Literal
from typing_extensions import TypedDict

from langchain_openai import ChatOpenAI

### Edges
llm = ChatOpenAI(
    temperature=0,
    model="GLM-4-plus",
    openai_api_key="your api key",
    openai_api_base="https://open.bigmodel.cn/api/paas/v4/"
)


members = ["researcher", "coder"]
# Our team supervisor is an LLM node. It just picks the next agent to process
# and decides when the work is completed
options = members + ["FINISH"]

system_prompt = (
    "You are a supervisor tasked with managing a conversation between the"
    f" following workers: {members}. Given the following user request,"
    " respond with the worker to act next. Each worker will perform a"
    " task and respond with their results and status. When finished,"
    " respond with FINISH."
)



from langchain_core.messages import HumanMessage
from langgraph.graph import StateGraph, START, END
from langgraph.prebuilt import create_react_agent


class Router(TypedDict):
    """Worker to route to next. If no workers needed, response 'FINISH'."""

    next: Literal[*options]



async def supervisor_node(state: AgentState) -> AgentState:
    messages = [
        {"role": "system", "content": system_prompt},
    ] + state["messages"]
    response = await llm.with_structured_output(Router).ainvoke(messages)
    next_ = response["next"]
    if "FINISH" in next_:
        next_ = END

    return {"next": next_}

research_agent = create_react_agent(
    llm, tools=[tavily_tool], state_modifier="You only provide information. Don't do the math."
)


async def research_node(state: AgentState) -> AgentState:
    result = await research_agent.ainvoke(state)
    return {
        "messages": [
            HumanMessage(content=result["messages"][-1].content, name="researcher")
        ]
    }


# NOTE: THIS PERFORMS ARBITRARY CODE EXECUTION, WHICH CAN BE UNSAFE WHEN NOT SANDBOXED
code_agent = create_react_agent(llm, tools=[code_executor],
                state_modifier="""
                when you use the code tool,it only detect the code block in markdown format.
                """             
            )


async def code_node(state: AgentState) -> AgentState:
    result = await code_agent.ainvoke(state)
    return {
        "messages": [HumanMessage(content=result["messages"][-1].content, name="coder")]
    }


builder = StateGraph(AgentState)
builder.add_edge(START, "supervisor")
builder.add_node("supervisor", supervisor_node)
builder.add_node("researcher", research_node)
builder.add_node("coder", code_node)
<langgraph.graph.state.StateGraph at 0x23c52d56c60>

3. graph中的边定义

for member in members:
    # We want our workers to ALWAYS "report back" to the supervisor when done
    builder.add_edge(member, "supervisor")

# The supervisor populates the "next" field in the graph state
# which routes to a node or finishes
builder.add_conditional_edges("supervisor", lambda state: state["next"])
# Finally, add entrypoint
builder.add_edge(START, "supervisor")

graph = builder.compile()
from IPython.display import display, Image
display(Image(graph.get_graph().draw_mermaid_png()))

请添加图片描述

4. 示例

4.1 第一个例子

问题: What's the square root of 42?

async for s in graph.astream(
    {"messages": [("user", "What's the square root of 42?")]}, subgraphs=True
):
    print(s)
    print("----")
((), {'supervisor': {'next': 'coder'}})
----
(('coder:7c74ccb6-c024-13da-c40d-83d4f5bb3251',), {'agent': {'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_-9181532423403291248', 'function': {'arguments': '{"code": "import math\\nprint(math.sqrt(42))"}', 'name': 'code_executor'}, 'type': 'function', 'index': 0}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 18, 'prompt_tokens': 190, 'total_tokens': 208, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'GLM-4-plus', 'system_fingerprint': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-d809acc4-d589-4227-ae66-96a4908305bc-0', tool_calls=[{'name': 'code_executor', 'args': {'code': 'import math\nprint(math.sqrt(42))'}, 'id': 'call_-9181532423403291248', 'type': 'tool_call'}], usage_metadata={'input_tokens': 190, 'output_tokens': 18, 'total_tokens': 208, 'input_token_details': {}, 'output_token_details': {}})]}})
----
(('coder:7c74ccb6-c024-13da-c40d-83d4f5bb3251',), {'tools': {'messages': [ToolMessage(content='The result is:6.48074069840786\n', name='code_executor', id='9127536d-111b-4de9-9ecf-769a369e619d', tool_call_id='call_-9181532423403291248')]}})
----
(('coder:7c74ccb6-c024-13da-c40d-83d4f5bb3251',), {'agent': {'messages': [AIMessage(content='The square root of 42 is approximately 6.4807.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 16, 'prompt_tokens': 225, 'total_tokens': 241, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'GLM-4-plus', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-b7554cd1-c355-4ad4-8482-5a27ad2afa9a-0', usage_metadata={'input_tokens': 225, 'output_tokens': 16, 'total_tokens': 241, 'input_token_details': {}, 'output_token_details': {}})]}})
----
((), {'coder': {'messages': [HumanMessage(content='The square root of 42 is approximately 6.4807.', additional_kwargs={}, response_metadata={}, name='coder')]}})
----
((), {'supervisor': {'next': '__end__'}})
----

4.2 第二个例子

问题:Find the latest GDP of New York and California, then calculate the average

async for s in graph.astream(
    {
        "messages": [
            (
                "user",
                "Find the latest GDP of New York and California, then calculate the average",
            )
        ]
    },
    subgraphs=True,
):
    print(s)
    print("----")
((), {'supervisor': {'next': 'researcher'}})
----
(('researcher:1c6c3cb9-b2d8-3632-e480-a307b53f1d77',), {'agent': {'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_-9181536546572673495', 'function': {'arguments': '{"query": "latest GDP of New York 2023"}', 'name': 'tavily_search_results_json'}, 'type': 'function', 'index': 0}, {'id': 'call_-9181536546572673494', 'function': {'arguments': '{"query": "latest GDP of California 2023"}', 'name': 'tavily_search_results_json'}, 'type': 'function', 'index': 1}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 41, 'prompt_tokens': 170, 'total_tokens': 211, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'GLM-4-plus', 'system_fingerprint': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-7553ea17-b477-45ff-973b-15c3584bfca9-0', tool_calls=[{'name': 'tavily_search_results_json', 'args': {'query': 'latest GDP of New York 2023'}, 'id': 'call_-9181536546572673495', 'type': 'tool_call'}, {'name': 'tavily_search_results_json', 'args': {'query': 'latest GDP of California 2023'}, 'id': 'call_-9181536546572673494', 'type': 'tool_call'}], usage_metadata={'input_tokens': 170, 'output_tokens': 41, 'total_tokens': 211, 'input_token_details': {}, 'output_token_details': {}})]}})
----
(('researcher:1c6c3cb9-b2d8-3632-e480-a307b53f1d77',), {'tools': {'messages': [ToolMessage(content='[{"url": "https://countryeconomy.com/gdp/usa-states/new-york", "content": "New York - GDP at market prices 2023 | countryeconomy.com US States GDP at market prices New York - GDP at market prices | 2023 | €2,008,702M | $2,172,010M | 1.5% | | 2022 | €1,949,439M | $2,052,759M | 1.7% | | 2021 | €1,626,290M | $1,923,413M | 4.8% | | 2020 | €1,552,591M | $1,773,370M | -2.8% | | 2019 | €1,596,669M | $1,787,471M | 2.4% | Evolution: GDP growth rate at constant prices New York Argentina: Fitch:Long Term Foreign currency Sovereign rating Barbados: Fitch:Long Term Foreign currency Sovereign rating Croatia: Fitch:Long Term Foreign currency Sovereign rating Egypt: Fitch:Long Term Foreign currency Sovereign rating Mongolia: Fitch:Long Term Foreign currency Sovereign rating Tunisia: Fitch:Long Term Foreign currency Sovereign rating"}, {"url": "https://www.bls.gov/regions/northeast/summary/blssummary_newyorkcity.pdf", "content": "New York City Economic Summary. Updated November 01, 2024. ... May 2023 New York area United States $39.45 $31.48 Prices paid by urban consumers for selected categories, over-the-year change Selling prices received by producers for selected industries nationwide, over-the-year change"}, {"url": "https://fred.stlouisfed.org/series/NYNGSP", "content": "Gross Domestic Product: All Industry Total in New York (NYNGSP) | FRED | St. Louis Fed FRED   About FRED About FRED What is FRED Gross Domestic Product: All Industry Total in New York (NYNGSP) Add data series to graph: U.S. Bureau of Economic Analysis, Gross Domestic Product: All Industry Total in New York [NYNGSP], retrieved from FRED, Federal Reserve Bank of St. Louis; https://fred.stlouisfed.org/series/NYNGSP, November 18, 2024. Real Gross Domestic Product: All Industry Total in New York Gross Domestic Product: All Industry Total in New Jersey Gross Domestic Product: All Industry Total in New York Gross State Product New York State Bureau of Economic Analysis Industry Gross Domestic Product Annual Public Domain: Citation Requested Not Seasonally Adjusted United States of America"}]', name='tavily_search_results_json', id='9ed353fe-b950-4b5f-9df1-4bc94514c3c4', tool_call_id='call_-9181536546572673495', artifact={'query': 'latest GDP of New York 2023', 'follow_up_questions': None, 'answer': None, 'images': [], 'results': [{'title': 'New York - GDP at market prices 2023 | countryeconomy.com', 'url': 'https://countryeconomy.com/gdp/usa-states/new-york', 'content': 'New York - GDP at market prices 2023 | countryeconomy.com US States GDP at market prices New York - GDP at market prices | 2023 | €2,008,702M | $2,172,010M | 1.5% | | 2022 | €1,949,439M | $2,052,759M | 1.7% | | 2021 | €1,626,290M | $1,923,413M | 4.8% | | 2020 | €1,552,591M | $1,773,370M | -2.8% | | 2019 | €1,596,669M | $1,787,471M | 2.4% | Evolution: GDP growth rate at constant prices New York Argentina: Fitch:Long Term Foreign currency Sovereign rating Barbados: Fitch:Long Term Foreign currency Sovereign rating Croatia: Fitch:Long Term Foreign currency Sovereign rating Egypt: Fitch:Long Term Foreign currency Sovereign rating Mongolia: Fitch:Long Term Foreign currency Sovereign rating Tunisia: Fitch:Long Term Foreign currency Sovereign rating', 'score': 0.99852777, 'raw_content': None}, {'title': 'PDF', 'url': 'https://www.bls.gov/regions/northeast/summary/blssummary_newyorkcity.pdf', 'content': 'New York City Economic Summary. Updated November 01, 2024. ... May 2023 New York area United States $39.45 $31.48 Prices paid by urban consumers for selected categories, over-the-year change Selling prices received by producers for selected industries nationwide, over-the-year change', 'score': 0.98862445, 'raw_content': None}, {'title': 'Gross Domestic Product: All Industry Total in New York', 'url': 'https://fred.stlouisfed.org/series/NYNGSP', 'content': 'Gross Domestic Product: All Industry Total in New York (NYNGSP) | FRED | St. Louis Fed FRED   About FRED About FRED What is FRED Gross Domestic Product: All Industry Total in New York (NYNGSP) Add data series to graph: U.S. Bureau of Economic Analysis, Gross Domestic Product: All Industry Total in New York [NYNGSP], retrieved from FRED, Federal Reserve Bank of St. Louis; https://fred.stlouisfed.org/series/NYNGSP, November 18, 2024. Real Gross Domestic Product: All Industry Total in New York Gross Domestic Product: All Industry Total in New Jersey Gross Domestic Product: All Industry Total in New York Gross State Product New York State Bureau of Economic Analysis Industry Gross Domestic Product Annual Public Domain: Citation Requested Not Seasonally Adjusted United States of America', 'score': 0.85452086, 'raw_content': None}], 'response_time': 1.76}), ToolMessage(content='[{"url": "https://www.gov.ca.gov/2024/04/16/california-remains-the-worlds-5th-largest-economy/", "content": "California remains the 5th largest economy in the world since 2017. California is the 5th largest economy in the world for the seventh consecutive year, with a nominal GDP of nearly $3.9 trillion in 2023 and a growth rate of 6.1% since the year prior, according to the U.S. Bureau of Economic Analysis (BEA). On a per capita basis, California is"}, {"url": "https://www.statista.com/statistics/187834/gdp-of-the-us-federal-state-of-california-since-1997/", "content": "Industry Overview\\nDigital & Trend reports\\nOverview and forecasts on trending topics\\nIndustry & Market reports\\nIndustry and market insights and forecasts\\nCompanies & Products reports\\nKey figures and rankings about companies and products\\nConsumer & Brand reports\\nConsumer and brand insights and preferences in various industries\\nPolitics & Society reports\\nDetailed information about political and social topics\\nCountry & Region reports\\nAll key figures about countries and regions\\nMarket forecast and expert KPIs for 1000+ markets in 190+ countries & territories\\nInsights on consumer attitudes and behavior worldwide\\nBusiness information on 100m+ public and private companies\\nExplore Company Insights\\nDetailed information for 39,000+ online stores and marketplaces\\nDirectly accessible data for 170 industries from 150+ countries\\nand over 1\xa0Mio. facts.\\n Statistics on\\n\\"\\nCalifornia\\n\\"\\nOther statistics that may interest you California\\nPopulation\\nEconomy\\nEmployment & Earnings\\nState & Local Government\\nMetro Areas\\nFurther related statistics\\nFurther Content: You might find this interesting as well\\nStatistics\\nTopics Other statistics on the topicCalifornia\\nEconomy\\nU.S. leading companies headquartered in California 2023, by number of employees\\nEconomy\\nU.S. average annual wages in California 2018-2026\\nEconomy\\nU.S. California fastest growing private companies 2023, by three year growth rate\\nResidential Real Estate\\nHourly wages needed to afford a two-bedroom apartment in California 2021-23, by metro\\nYou only have access to basic statistics.\\n Additional Information\\nShow sources information\\nShow publisher information\\nUse Ask Statista Research Service\\nMarch 2023\\nUnited States\\n2000 to 2022\\nData presented here is in 2012 chained U.S. dollars.\\n Transforming data into design:\\nStatista Content & Design\\nStrategy and business building for the data-driven economy:\\nU.S. real GDP of California 2000-2022\\nReal gross domestic product of California in the United States from 2000 to 2022\\n(in billion U.S. dollars)\\n"}, {"url": "https://www.bea.gov/news/2024/gross-domestic-product-fourth-quarter-and-year-2023-advance-estimate", "content": "Gross Domestic Product, Fourth Quarter and Year 2023 (Advance Estimate) | U.S. Bureau of Economic Analysis (BEA) Real gross domestic product (GDP) increased at an annual rate of 3.3 percent in the fourth quarter of 2023 (table 1), according to the \\"advance\\" estimate released by the Bureau of Economic Analysis. The price index for gross domestic purchases increased 1.9 percent in the fourth quarter, compared with an increase of 2.9 percent in the third quarter (table 4). BEA releases three vintages of the current quarterly estimate for GDP. Unlike GDP, advance current quarterly estimates of GDI and corporate profits are not released because data on domestic profits and net interest of domestic industries are not available."}]', name='tavily_search_results_json', id='ae678022-d845-45fc-8273-e6d145ee952d', tool_call_id='call_-9181536546572673494', artifact={'query': 'latest GDP of California 2023', 'follow_up_questions': None, 'answer': None, 'images': [], 'results': [{'title': "California Remains the World's 5th Largest Economy", 'url': 'https://www.gov.ca.gov/2024/04/16/california-remains-the-worlds-5th-largest-economy/', 'content': 'California remains the 5th largest economy in the world since 2017. California is the 5th largest economy in the world for the seventh consecutive year, with a nominal GDP of nearly $3.9 trillion in 2023 and a growth rate of 6.1% since the year prior, according to the U.S. Bureau of Economic Analysis (BEA). On a per capita basis, California is', 'score': 0.9961755, 'raw_content': None}, {'title': 'Real GDP California U.S. 2023 | Statista', 'url': 'https://www.statista.com/statistics/187834/gdp-of-the-us-federal-state-of-california-since-1997/', 'content': 'Industry Overview\nDigital & Trend reports\nOverview and forecasts on trending topics\nIndustry & Market reports\nIndustry and market insights and forecasts\nCompanies & Products reports\nKey figures and rankings about companies and products\nConsumer & Brand reports\nConsumer and brand insights and preferences in various industries\nPolitics & Society reports\nDetailed information about political and social topics\nCountry & Region reports\nAll key figures about countries and regions\nMarket forecast and expert KPIs for 1000+ markets in 190+ countries & territories\nInsights on consumer attitudes and behavior worldwide\nBusiness information on 100m+ public and private companies\nExplore Company Insights\nDetailed information for 39,000+ online stores and marketplaces\nDirectly accessible data for 170 industries from 150+ countries\nand over 1\xa0Mio. facts.\n Statistics on\n"\nCalifornia\n"\nOther statistics that may interest you California\nPopulation\nEconomy\nEmployment & Earnings\nState & Local Government\nMetro Areas\nFurther related statistics\nFurther Content: You might find this interesting as well\nStatistics\nTopics Other statistics on the topicCalifornia\nEconomy\nU.S. leading companies headquartered in California 2023, by number of employees\nEconomy\nU.S. average annual wages in California 2018-2026\nEconomy\nU.S. California fastest growing private companies 2023, by three year growth rate\nResidential Real Estate\nHourly wages needed to afford a two-bedroom apartment in California 2021-23, by metro\nYou only have access to basic statistics.\n Additional Information\nShow sources information\nShow publisher information\nUse Ask Statista Research Service\nMarch 2023\nUnited States\n2000 to 2022\nData presented here is in 2012 chained U.S. dollars.\n Transforming data into design:\nStatista Content & Design\nStrategy and business building for the data-driven economy:\nU.S. real GDP of California 2000-2022\nReal gross domestic product of California in the United States from 2000 to 2022\n(in billion U.S. dollars)\n', 'score': 0.60323083, 'raw_content': None}, {'title': 'Gross Domestic Product, Fourth Quarter and Year 2023 (Advance Estimate)', 'url': 'https://www.bea.gov/news/2024/gross-domestic-product-fourth-quarter-and-year-2023-advance-estimate', 'content': 'Gross Domestic Product, Fourth Quarter and Year 2023 (Advance Estimate) | U.S. Bureau of Economic Analysis (BEA) Real gross domestic product (GDP) increased at an annual rate of 3.3 percent in the fourth quarter of 2023 (table 1), according to the "advance" estimate released by the Bureau of Economic Analysis. The price index for gross domestic purchases increased 1.9 percent in the fourth quarter, compared with an increase of 2.9 percent in the third quarter (table 4). BEA releases three vintages of the current quarterly estimate for GDP. Unlike GDP, advance current quarterly estimates of GDI and corporate profits are not released because data on domestic profits and net interest of domestic industries are not available.', 'score': 0.5940803, 'raw_content': None}], 'response_time': 2.92})]}})
----
(('researcher:1c6c3cb9-b2d8-3632-e480-a307b53f1d77',), {'agent': {'messages': [AIMessage(content="The latest GDP of New York in 2023 is approximately $2,172,010 million, and the latest GDP of California in 2023 is nearly $3.9 trillion, which is $3,900,000 million.\n\nTo calculate the average GDP of the two states, you would add these two figures together and then divide by 2. \n\nPlease note that for accurate calculations, it's important to ensure that the units are consistent (both in millions or both in trillions). The figures provided here are in millions. \n\nYou can proceed with the calculation using these figures.", additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 121, 'prompt_tokens': 1587, 'total_tokens': 1708, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'GLM-4-plus', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-752b03c7-f372-447d-9440-97b513f0ae2b-0', usage_metadata={'input_tokens': 1587, 'output_tokens': 121, 'total_tokens': 1708, 'input_token_details': {}, 'output_token_details': {}})]}})
----
((), {'researcher': {'messages': [HumanMessage(content="The latest GDP of New York in 2023 is approximately $2,172,010 million, and the latest GDP of California in 2023 is nearly $3.9 trillion, which is $3,900,000 million.\n\nTo calculate the average GDP of the two states, you would add these two figures together and then divide by 2. \n\nPlease note that for accurate calculations, it's important to ensure that the units are consistent (both in millions or both in trillions). The figures provided here are in millions. \n\nYou can proceed with the calculation using these figures.", additional_kwargs={}, response_metadata={}, name='researcher')]}})
----
((), {'supervisor': {'next': 'coder'}})
----
(('coder:08b90861-7717-a01e-8178-a2245ce71495',), {'agent': {'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_-9181530190019420575', 'function': {'arguments': '{\n    "code": "def calculate_average_gdp(gdp_new_york, gdp_california):\\n    return (gdp_new_york + gdp_california) / 2\\n\\n# GDP values in millions\\nlatest_gdp_new_york = 2172010\\nlatest_gdp_california = 3900000\\n\\naverage_gdp = calculate_average_gdp(latest_gdp_new_york, latest_gdp_california)\\nprint(f\\"The average GDP of New York and California is: {average_gdp} million\\")\\n"\n}', 'name': 'code_executor'}, 'type': 'function', 'index': 0}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 123, 'prompt_tokens': 316, 'total_tokens': 439, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'GLM-4-plus', 'system_fingerprint': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-ccf3ab4e-8e24-480c-8935-b09236974eeb-0', tool_calls=[{'name': 'code_executor', 'args': {'code': 'def calculate_average_gdp(gdp_new_york, gdp_california):\n    return (gdp_new_york + gdp_california) / 2\n\n# GDP values in millions\nlatest_gdp_new_york = 2172010\nlatest_gdp_california = 3900000\n\naverage_gdp = calculate_average_gdp(latest_gdp_new_york, latest_gdp_california)\nprint(f"The average GDP of New York and California is: {average_gdp} million")\n'}, 'id': 'call_-9181530190019420575', 'type': 'tool_call'}], usage_metadata={'input_tokens': 316, 'output_tokens': 123, 'total_tokens': 439, 'input_token_details': {}, 'output_token_details': {}})]}})
----
(('coder:08b90861-7717-a01e-8178-a2245ce71495',), {'tools': {'messages': [ToolMessage(content='The result is:The average GDP of New York and California is: 3036005.0 million\n', name='code_executor', id='63ae3dcf-e81d-49f9-a705-1d87091554e8', tool_call_id='call_-9181530190019420575')]}})
----
(('coder:08b90861-7717-a01e-8178-a2245ce71495',), {'agent': {'messages': [AIMessage(content='The average GDP of New York and California is approximately 3,036,005 million. This figure represents the midpoint of their respective GDPs, providing a general sense of the economic scale of these two states combined.', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 47, 'prompt_tokens': 459, 'total_tokens': 506, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'GLM-4-plus', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-df630065-cd91-45ba-9fab-376ec79f9f60-0', usage_metadata={'input_tokens': 459, 'output_tokens': 47, 'total_tokens': 506, 'input_token_details': {}, 'output_token_details': {}})]}})
----
((), {'coder': {'messages': [HumanMessage(content='The average GDP of New York and California is approximately 3,036,005 million. This figure represents the midpoint of their respective GDPs, providing a general sense of the economic scale of these two states combined.', additional_kwargs={}, response_metadata={}, name='coder')]}})
----
((), {'supervisor': {'next': '__end__'}})
----

参考链接:https://langchain-ai.github.io/langgraph/tutorials/multi_agent/agent_supervisor/

如果有任何问题,欢迎在评论区提问。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2254403.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【Maven系列】深入解析 Maven 镜像配置

前言 Maven 是一个流行的 Java 项目管理和构建工具&#xff0c;可以自动化构建项目、管理依赖、生成报告等。在Maven构建项目时&#xff0c;通常经常需要下载各种依赖。默认情况下&#xff0c;Maven 会从中央仓库下载这些依赖&#xff0c;但在某些情况下&#xff0c;这个过程可…

HTML 添加 文本水印

body,html {margin: 0;height: 100vh;width: 100vw;} // 自定义文案const setting {text: "水印文案", // 水印内容innerDate: true, // 在水印下方增加日期width: 110, // 水印宽度};// 自定义文字水印const watermark (function () {return {build: function (a…

华为HCIE-Datacom认证笔试+实验考试介绍

华为HCIE数通认证考试是面向那些希望成为数通网络领域专家的人员&#xff0c;考试通常两部分&#xff1a;笔试和实验考试。 考试科目&#xff1a; HCIE-Datacom笔试考试内容&#xff1a; HCIE-Datacom V1.0考试覆盖数据通信领域路由交换高阶技术、企业网络架构全景、园区网络…

PyCharm+Selenium+Pytest配置小记

1、下载ChromeDriver&#xff1a; Chrome130以后的Driver下载&#xff1a; Chrome for Testing availabilityhttps://googlechromelabs.github.io/chrome-for-testing/ &#xff08;1&#xff09;查看自己Crome浏览器的版本&#xff1a;设置-->关于 Chrome&#xff1b; &…

我们来学webservie - WSDL

WSDL 题记WSDL系列文章 题记 举个例子 酒桌上大领导们谈笑风生&#xff0c;把酒临风,其喜洋洋者矣老张说能签下xx项目&#xff0c;一来证明了集团在行业中的翘楚地位&#xff0c;二来感谢各位领导给予的大力支持接下来的一周&#xff0c;项目经理、业务顾问相继入场&#xff0…

weblogic开启https

JSK证书生成 生成密钥库和证书 使用Java的keytool命令来生成一个Java密钥库&#xff08;Keystore&#xff09;和证书。keytool是Java开发工具包&#xff08;JDK&#xff09;中用于管理密钥库和证书的命令行工具。 #创建证书存放目录 [weblogicosb1 jksHL]$ mkdir -p /home/w…

激活函数在神经网络中的应用与选择

目录 ​编辑 Sigmoid函数 代码示例与分析 Tanh函数 代码示例与分析 ReLU函数 代码示例与分析 Leaky ReLU函数 代码示例与分析 PReLU函数 代码示例与分析 ELU函数 代码示例与分析 SELU函数 代码示例与分析 Softmax函数 代码示例与分析 结论 在深度学习领域&am…

使用Tauri创建桌面应用

当前是在 Windows 环境下 1.准备 系统依赖项 Microsoft C 构建工具WebView2 (Windows10 v1803 以上版本不用下载&#xff0c;已经默认安装了) 下载安装 Rust下载安装 Rust 需要重启终端或者系统 重新打开cmd&#xff0c;键入rustc --version&#xff0c;出现 rust 版本号&…

2023年第十四届蓝桥杯Scratch国赛真题—推箱子

推箱子 程序演示及其源码解析&#xff0c;可前往&#xff1a; https://www.hixinao.com/scratch/creation/show-188.html 若需在线编程&#xff0c;在线测评模考&#xff0c;助力赛事可自行前往题库中心&#xff0c;按需查找&#xff1a; https://www.hixinao.com/ 题库涵盖…

[RabbitMQ] RabbitMQ常见应用问题

&#x1f338;个人主页:https://blog.csdn.net/2301_80050796?spm1000.2115.3001.5343 &#x1f3f5;️热门专栏: &#x1f9ca; Java基本语法(97平均质量分)https://blog.csdn.net/2301_80050796/category_12615970.html?spm1001.2014.3001.5482 &#x1f355; Collection与…

HarmonyOS 5.0应用开发——UIAbility生命周期

【高心星出品】 文章目录 UIAbility组件创建AbilityUIAbility的生命周期Create状态WindowStageCreate状态Foreground和Background状态WindowStageWillDestroy状态Destroy状态 UIAbility组件 UIAbility组件是一种包含UI的应用组件&#xff0c;主要用于和用户交互。 UIAbility组…

Coovally CPU版:用AI模型微调技术革新数据标注方式

文章目录 前言一、为什么选择Coovally CPU版&#xff1f;1.微调模型更懂你的数据2.省时省力的标注流程3.零GPU门槛&#xff0c;适配性强 二、教程&#xff1a;如何用Coovally CPU版完成高效数据标注&#xff1f;第一步&#xff1a;安装Coovally CPU版第二步&#xff1a;加载数据…

Lua元表和元方法的使用

元表是一个普通的 Lua 表&#xff0c;包含一组元方法&#xff0c;这些元方法与 Lua 中的事件相关联。事件发生在 Lua 执行某些操作时&#xff0c;例如加法、字符串连接、比较等。元方法是普通的 Lua 函数&#xff0c;在特定事件发生时被调用。 元表包含了以下元方法&#xff1…

【初阶数据结构与算法】二叉树链式结构的定义与实现万字笔记(附源码)

文章目录 一、二叉树链式结构的定义二、二叉树链式结构功能的基本实现1.链式二叉树的手动创建2.链式二叉树的前中后序遍历前序遍历中序遍历后序遍历 3.链式二叉树节点的个数4.链式二叉树叶子节点的个数5.链式二叉树的高度/深度6.链式二叉树第k层节点的个数7.链式二叉树的查找8.…

前端框架的选择与反思:在简约与复杂之间寻找平衡

在当今互联网时代&#xff0c;前端开发已经成为web应用构建中不可或缺的一环。从最初的静态HTML页面&#xff0c;到如今复杂的单页应用&#xff08;SPA&#xff09;&#xff0c;前端技术的发展让我们见证了Web应用的蓬勃发展。然而&#xff0c;伴随着技术的进步&#xff0c;一个…

SABO-CNN-BiGRU-Attention减法优化器优化卷积神经网络结合双向门控循环单元时间序列预测,含优化前后对比

SABO-CNN-BiGRU-Attention减法优化器优化卷积神经网络结合双向门控循环单元时间序列预测&#xff0c;含优化前后对比 目录 SABO-CNN-BiGRU-Attention减法优化器优化卷积神经网络结合双向门控循环单元时间序列预测&#xff0c;含优化前后对比预测效果基本介绍模型描述程序设计参…

SpringBoot期末知识点大全

一、学什么 IoC AOP&#xff1a;面向切面编程。 事物处理 整合MyBatis Spring框架思想&#xff01; 二、核心概念 问题&#xff1a;类之间互相调用/实现&#xff0c;导致代码耦合度高。 解决&#xff1a;使用对象时&#xff0c;程序中不主动new对象&#xff0c;转换为由外部提…

撰写技术文档的关键步骤和核心要点

编写项目的技术文档是一个重要且细致的任务&#xff0c;它不仅有助于项目的当前开发团队理解系统的结构和工作原理&#xff0c;还为未来的维护和扩展提供了宝贵的参考资料。以下是撰写技术文档时应遵循的几个关键步骤和组成部分&#xff1a; 1. 概述 项目简介&#xff1a;简要…

【人工智能】Transformers之Pipeline(二十八):视觉问答(visual-question-answering)

​​​​​​​ 目录 一、引言 二、视觉问答&#xff08;visual-question-answering&#xff09; 2.1 概述 2.2 dandelin/ViLT 2.3 pipeline参数 2.3.1 pipeline对象实例化参数 2.3.2 pipeline对象使用参数 2.3.3 pipeline对象返回参数 2.4 pipeline实战 2.5 模型…

【Vue3】详解Vue3的ref与reactive:两者的区别与使用场景

文章目录 引言Moss前沿AIVue 3响应式系统概述ref与reactive的基础概念ref与reactive的区别1. 数据类型2. 访问方式3. 响应式追踪机制4. 可变性5. 使用场景表格对比 ref与reactive的使用场景1. 选择ref的场景2. 选择reactive的场景 性能分析与优化建议1. 响应式系统的性能优势2.…