langgraph / / 2024. 11. 21. 17:55

[langgraph] Multi-agent Network

langgraph의 공식문서를 번역해 놓은 자료입니다. 필요한 경우 부연 설명을 추가하였습니다. 문제가 되면 삭제하겠습니다.

https://langchain-ai.github.io/langgraph/tutorials/multi_agent/multi-agent-collaboration/

하나의 에이전트는 일반적으로 하나의 도메인 내에서 몇 가지 도구만 사용해도 효과적으로 작업을 수행할 수 있지만, GPT-4와 같은 강력한 모델을 사용하더라도 많은 도구를 사용할 때는 효율이 떨어질 수 있다.

복잡한 작업을 해결하는 한 가지 방법은 "분할 정복(divide-and-conquer)" 접근법을 사용하는 것이다. 각 작업이나 도메인에 특화된 에이전트를 만들고, 해당 작업을 적합한 "전문가"에게 라우팅하는 방식이다. 이것은 다중 에이전트 네트워크 아키텍처의 한 예시이다.

이 노트북은 Wu 외 연구진이 작성한 논문 AutoGen: Enabling Next-Gen LLM Applications via Multi-Agent Conversation에서 영감을 받아, LangGraph를 사용해 이를 구현하는 방법을 보여준다.

이렇게 만들어진 그래프는 다음과 같은 다이어그램 형태가 될 것이다.

시작하기 전에 간단한 안내를 하자면, 이 예시와 다른 다중 에이전트 노트북들은 LangGraph에서 특정 디자인 패턴을 어떻게 구현할 수 있는지 보여주기 위해 설계되었다. 이 패턴이 여러분의 요구 사항에 맞는다면, 최상의 성능을 위해 이 패턴을 문서에서 설명된 다른 기본적인 패턴들과 함께 사용하는 것을 권장한다.

준비

먼저, 필요한 패키지들을 설치하고 API 키를 설정해 보자.

%pip install -U langchain langchain_openai langsmith pandas langchain_experimental matplotlib langgraph langchain_core

.env에 OPENAI_API_KEY와 TAVILY_API_KEY를 설정한다.

from dotenv import load_dotenv

load_dotenv()

.env

OPENAI_API_KEY=sk_xxx
TAVILY_API_KEY=xxxxxx

Agents 생성

다음의 헬퍼 함수들은 에이전트를 생성하는 데 사용된다. 이 에이전트들은 이후 그래프의 노드가 될 것이다.

그래프의 모습만 보고 싶다면, 바로 다음으로 넘어가도 좋다.

from langchain_core.messages import (
    BaseMessage,
    HumanMessage,
    ToolMessage,
)
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

from langgraph.graph import END, StateGraph, START


def create_agent(llm, tools, system_message: str):
    """Create an agent."""
    prompt = ChatPromptTemplate.from_messages(
        [
            (
                "system",
                "You are a helpful AI assistant, collaborating with other assistants."
                " Use the provided tools to progress towards answering the question."
                " If you are unable to fully answer, that's OK, another assistant with different tools "
                " will help where you left off. Execute what you can to make progress."
                " If you or any of the other assistants have the final answer or deliverable,"
                " prefix your response with FINAL ANSWER so the team knows to stop."
                " You have access to the following tools: {tool_names}.\n{system_message}",
            ),
            MessagesPlaceholder(variable_name="messages"),
        ]
    )
    prompt = prompt.partial(system_message=system_message)
    prompt = prompt.partial(tool_names=", ".join([tool.name for tool in tools]))
    return prompt | llm.bind_tools(tools)

이후에 create_agent는 research_agent와 chart_agent를 만드는 데 사용된다. research_agent는 tavily_tool로 검색을 하는 역할을 하고 chart_agent는 python_repl으로 차트를 생성하는 데 사용된다.

tools 정의

또한, 앞으로 에이전트들이 사용할 몇 가지 도구도 정의한다.

from typing import Annotated

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

# 검색도구
tavily_tool = TavilySearchResults(max_results=5)
# 차트 생성 도구
repl = PythonREPL()


@tool
def python_repl(
    code: Annotated[str, "The python code to execute to generate your chart."],
):
    """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 = repl.run(code)
    except BaseException as e:
        return f"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."
    )

graph 생성

이제 도구들을 정의하고 헬퍼 함수들을 만들었으니, 아래에서 각각의 에이전트를 생성하고 LangGraph를 사용해 이들이 서로 소통하는 방식을 설정하자.

State 정의

먼저 그래프의 상태(state)를 정의하자. 여기서는 메시지 목록과 가장 최근의 발신자를 추적할 키를 포함한다.

import operator
from typing import Annotated, Sequence
from typing_extensions import TypedDict

from langchain_openai import ChatOpenAI


# 여기서 각 노드에서 전달되는 객체를 정의한다.
# 그래프에서 각 에이전트와 도구에 다른 노드를 생성한다.
class AgentState(TypedDict):
    messages: Annotated[Sequence[BaseMessage], operator.add]
    sender: str

Agent Node 정의

이제 노드를 정의한다. 먼저, 에이전트를 위한 노드들을 정의해 보자.

import functools

from langchain_core.messages import AIMessage


# 해당 에이전트의 노드를 만드는데 필요한 헬퍼 함수
def agent_node(state, agent, name):
    result = agent.invoke(state)

    # 에이전트 출력을 전역 상태에 추가될 형식으로 변환한다.
    if isinstance(result, ToolMessage):
        pass
    else:
        result = AIMessage(**result.dict(exclude={"type", "name"}), name=name)
    return {
        "messages": [result],
        # 엄격한 워크플로우를 가지고 있기 때문에 다음에 누구에게 전달하는지 알 수 있다.
        "sender": name,
    }


llm = ChatOpenAI(model="gpt-4o")

# Research 에이전트와 노드
research_agent = create_agent(
    llm,
    [tavily_tool],
    system_message="You should provide accurate data for the chart_generator to use.",
)
research_node = functools.partial(agent_node, agent=research_agent, name="Researcher")

# chart_generator 에이전트와 노드
chart_agent = create_agent(
    llm,
    [python_repl],
    system_message="Any charts you display will be visible by the user.",
)
chart_node = functools.partial(agent_node, agent=chart_agent, name="chart_generator")

functions.partial은 기존 함수의 일부 인수를 고정하여 새로운 함수를 생성하는 데 사용된다.

def multiply(x, y):
 return x * y

# y를 2로 고정한 새로운 함수 생성
double = partial(multiply, y=2)

# 호출
result = double(5)  # multiply(5, 2)와 동일
print(result)  # 출력: 10

Tool Node 정의

도구를 실행하기 위한 노드를 정의한다.

from langgraph.prebuilt import ToolNode

tools = [tavily_tool, python_repl]
tool_node = ToolNode(tools)

Edge 로직 정의

이제 에이전트의 결과에 따라 다음 작업을 결정하기 위해 필요한 일부 엣지(edge) 로직을 정의하자.

from typing import Literal


def router(state):
    messages = state["messages"]
    last_message = messages[-1]
    if last_message.tool_calls:
        # 이전 에이전트가 tool 실행
        return "call_tool"
    if "FINAL ANSWER" in last_message.content:
        # 에이전트 작업이 완료되었음
        return END
    return "continue"

Graph 정의

이제 모든 요소를 종합하여 그래프를 정의할 수 있다.

workflow = StateGraph(AgentState)

workflow.add_node("Researcher", research_node)
workflow.add_node("chart_generator", chart_node)
workflow.add_node("call_tool", tool_node)

workflow.add_conditional_edges(
    "Researcher",
    router,
    {"continue": "chart_generator", "call_tool": "call_tool", END: END},
)
workflow.add_conditional_edges(
    "chart_generator",
    router,
    {"continue": "Researcher", "call_tool": "call_tool", END: END},
)

workflow.add_conditional_edges(
    "call_tool",
    # 각 에이전트는 'sender' 필드를 업데이트한다.
    # 도구를 호출하는 노드는 호출한 원래 에이전트로 돌아간다.
    lambda x: x["sender"],
    {
        "Researcher": "Researcher",
        "chart_generator": "chart_generator",
    },
)
workflow.add_edge(START, "Researcher")
graph = workflow.compile()
from IPython.display import Image, display

try:
    display(
        Image(
            graph.get_graph(xray=True).draw_mermaid_png(
                output_file_path="./network.png"
            )
        )
    )
except Exception:
    pass

실행

그래프가 생성되었으니, 이제 이를 호출하여 통계 등을 차트로 시각화할 수 있다.

events = graph.stream(
    {
        "messages": [
            HumanMessage(
                content="과거 5년 동안 한국의 GDP를 가져와서 라인 그래프로 그리고, 완료해줘~"
            )
        ],
    },
    # Maximum number of steps to take in the graph
    {"recursion_limit": 150},
)
for s in events:
    print(s)
    print("----")

실행결과

{
  'Researcher': {
    'messages': [
      AIMessage(content=
      '',
      additional_kwargs=
      {
        'tool_calls': [
          {
            'id': 'call_r9Dn5uIE7LIrPnRVDtc3s4yG',
            'function': {
              'arguments': '{"query": "South Korea GDP 2023"}',
              'name': 'tavily_search_results_json'
            },
            'type': 'function'
          },
          {
            'id': 'call_TFf9lqxwfmhf3Bx1EOTwcloz',
            'function': {
              'arguments': '{"query": "South Korea GDP 2022"}',
              'name': 'tavily_search_results_json'
            },
            'type': 'function'
          },
          {
            'id': 'call_ZI8CBhTMAxQ0VKzIPysfrSv3',
            'function': {
              'arguments': '{"query": "South Korea GDP 2021"}',
              'name': 'tavily_search_results_json'
            },
            'type': 'function'
          },
          {
            'id': 'call_V900ERmp5PfXlnBdUS1Ms4iN',
            'function': {
              'arguments': '{"query": "South Korea GDP 2020"}',
              'name': 'tavily_search_results_json'
            },
            'type': 'function'
          },
          {
            'id': 'call_hHdg2nLpfcPPM420iWRNHgMA',
            'function': {
              'arguments': '{"query": "South Korea GDP 2019"}',
              'name': 'tavily_search_results_json'
            },
            'type': 'function'
          }
        ],
        'refusal': None
      },
      response_metadata=
      {
        'token_usage': {
          'completion_tokens': 131,
          'prompt_tokens': 213,
          'total_tokens': 344,
          'completion_tokens_details': {
            'accepted_prediction_tokens': 0,
            'audio_tokens': 0,
            'reasoning_tokens': 0,
            'rejected_prediction_tokens': 0
          },
          'prompt_tokens_details': {
            'audio_tokens': 0,
            'cached_tokens': 0
          }
        },
        'model_name': 'gpt-4o-2024-08-06',
        'system_fingerprint': 'fp_7f6be3efb0',
        'finish_reason': 'tool_calls',
        'logprobs': None
      },
      name=
      'Researcher',
      id=
      'run-f273bc6e-9ac6-44a4-b3a6-19fc2efd7629-0',
      tool_calls=
      [
        {
          'name': 'tavily_search_results_json',
          'args': {
            'query': 'South Korea GDP 2023'
          },
          'id': 'call_r9Dn5uIE7LIrPnRVDtc3s4yG',
          'type': 'tool_call'
        },
        {
          'name': 'tavily_search_results_json',
          'args': {
            'query': 'South Korea GDP 2022'
          },
          'id': 'call_TFf9lqxwfmhf3Bx1EOTwcloz',
          'type': 'tool_call'
        },
        {
          'name': 'tavily_search_results_json',
          'args': {
            'query': 'South Korea GDP 2021'
          },
          'id': 'call_ZI8CBhTMAxQ0VKzIPysfrSv3',
          'type': 'tool_call'
        },
        {
          'name': 'tavily_search_results_json',
          'args': {
            'query': 'South Korea GDP 2020'
          },
          'id': 'call_V900ERmp5PfXlnBdUS1Ms4iN',
          'type': 'tool_call'
        },
        {
          'name': 'tavily_search_results_json',
          'args': {
            'query': 'South Korea GDP 2019'
          },
          'id': 'call_hHdg2nLpfcPPM420iWRNHgMA',
          'type': 'tool_call'
        }
      ],
      usage_metadata=
      {
        'input_tokens': 213,
        'output_tokens': 131,
        'total_tokens': 344,
        'input_token_details': {
          'audio': 0,
          'cache_read': 0
        },
        'output_token_details': {
          'audio': 0,
          'reasoning': 0
        }
      }
      )
    ],
    'sender': 'Researcher'
  }
}
----
{
  'call_tool': {
    'messages': [
      ToolMessage(content=
      '[{"url": "https://countryeconomy.com/gdp/south-korea?year=2023", "content": "Gross Domestic Product of South Korea grew 1.4% in 2023 compared to last year. (생략)...."}]',
      name=
      'tavily_search_results_json',
      tool_call_id=
      'call_r9Dn5uIE7LIrPnRVDtc3s4yG',
      artifact=
      {
        'query': 'South Korea GDP 2023',
        'follow_up_questions': None,
        'answer': None,
        'images': [],
        'results': [
          {
            'title': 'South Korea GDP - Gross Domestic Product 2023 - countryeconomy.com',
            'url': 'https://countryeconomy.com/gdp/south-korea?year=2023',
            'content': 'Gross Domestic Product of South Korea grew 1.4% in 2023 compared to last year. T...',
            'score': 0.99977833,
            'raw_content': None
          },
          {
            'title': 'South Korea GDP - TRADING ECONOMICS',
            'url': 'https://tradingeconomics.com/south-korea/gdp',
            'content': 'South Korea GDP Interest Rate South Korea GDP The Gross Domestic Product (GDP) in South Korea (생략).......',
            'score': 0.99974483,
            'raw_content': None
          },
          {
            'title': 'South Korea GDP Growth Rate 1961-2024 - Macrotrends',
            'url': 'https://www.macrotrends.net/global-metrics/countries/KOR/south-korea/gdp-growth-rate',
            'content': 'South Korea gdp growth rate for 2023 was 1.36%, a 1.26% decline from 2022. (생략)....',
            'score': 0.9995695,
            'raw_content': None
          },
          {
            'title': 'Nominal Gross Domestic Product for Republic of Korea (NGDPSAXDCKRQ) - FRED',
            'url': 'https://fred.stlouisfed.org/series/NGDPSAXDCKRQ',
            'content': 'Graph and download economic data for Nominal Gross Domestic Product for Republic of Korea (생략).......',
            'score': 0.9987056,
            'raw_content': None
          },
          {
            'title': 'PDF',
            'url': 'https://datacatalogfiles.worldbank.org/ddh-published/0038130/DR0046441/GDP.pdf?versionId=2024-07-01T12:42:23.8710032Z',
            'content': 'Gross domestic product 2023 (millions of Ranking Economy US dollars) ... 14 Korea, Rep. 1,712,793 15 Spain 1,580,695 (생략).....',
            'score': 0.98262435,
            'raw_content': None
          }
        ],
        'response_time': 2.2
      }
      ),
      ToolMessage(content=
      '[{"url": "https://countryeconomy.com/gdp/south-korea?year=2022", "content": "South Korea GDP - (생략)...."}]',
      name=
      'tavily_search_results_json',
      tool_call_id=
      'call_TFf9lqxwfmhf3Bx1EOTwcloz',
      artifact=
      {
        'query': 'South Korea GDP 2022',
        'follow_up_questions': None,
        'answer': None,
        'images': [],
        'results': [
          {
            'title': 'South Korea GDP - Gross Domestic Product 2022 - countryeconomy.com',
            'url': 'https://countryeconomy.com/gdp/south-korea?year=2022',
            'content': 'South Korea GDP - Gross Domestic Product 2022 | countryeconomy.com South Korea GDP - (생략)....',
            'score': 0.9998945,
            'raw_content': None
          },
          {
            'title': 'South Korea GDP 1960-2024 - Macrotrends',
            'url': 'https://www.macrotrends.net/global-metrics/countries/KOR/south-korea/gdp-gross-domestic-product',
            'content': "South Korea gdp for 2023 was (생략)....",
            'score': 0.99956435,
            'raw_content': None
          },
          {
            'title': 'South Korea GDP - Worldometer',
            'url': 'https://www.worldometers.info/gdp/south-korea-gdp/',
            'content': 'WGDPGDP by Country South Korea GDP South Korea GDP (생략)....',
            'score': 0.99948263,
            'raw_content': None
          },
          {
            'title': 'South Korea GDP Growth Rate 1961-2024 - Macrotrends',
            'url': 'https://www.macrotrends.net/global-metrics/countries/KOR/south-korea/gdp-growth-rate',
            'content': 'South Korea gdp growth rate for 2023 was 1.36%, a 1.26% decline from 2022. (생략)....',
            'score': 0.9991928,
            'raw_content': None
          },
          {
            'title': 'South Korea GDP - TRADING ECONOMICS',
            'url': 'https://tradingeconomics.com/south-korea/gdp',
            'content': 'South Korea GDP Interest Rate South Korea GDP The Gross Domestic Product (GDP) in South Korea was (생략).....',
            'score': 0.9981541,
            'raw_content': None
          }
        ],
        'response_time': 2.2
      }
      ),
      ToolMessage(content=
      '[{"url": "https://www.macrotrends.net/global-metrics/countries/KOR/south-korea/gdp-gross-domestic-product", "content": "South Korea gdp for 2021 was $1,818.43B, a 10.59% (생략)...."}]',
      name=
      'tavily_search_results_json',
      tool_call_id=
      'call_ZI8CBhTMAxQ0VKzIPysfrSv3',
      artifact=
      {
        'query': 'South Korea GDP 2021',
        'follow_up_questions': None,
        'answer': None,
        'images': [],
        'results': [
          {
            'title': 'South Korea GDP 1960-2024 - Macrotrends',
            'url': 'https://www.macrotrends.net/global-metrics/countries/KOR/south-korea/gdp-gross-domestic-product',
            'content': 'South Korea gdp for 2021 was $1,818.43B, a 10.59% increase from 2020. South Korea gdp for 2020 was (생략)....',
            'score': 0.99967504,
            'raw_content': None
          },
          {
            'title': 'South Korea Real GDP | Economic Indicators | CEIC - CEIC Data',
            'url': 'https://www.ceicdata.com/en/korea/governance-economic-environment-and-growth-oecd-member-annual/kr-real-gdp',
            'content': 'South Korea Real GDP data was reported at 2,234.186 USD bn in 2021. South Korea Real GDP data is updated yearly, .(생략)...',
            'score': 0.9996049,
            'raw_content': None
          },
          {
            'title': 'South Korea GDP - Gross Domestic Product 2021 - countryeconomy.com',
            'url': 'https://countryeconomy.com/gdp/south-korea?year=2021',
            'content': "Main navigation\nTop menu\nSouth Korea GDP - Gross Domestic Product\nGDP South Korea 2021\nGDP improves (생략)....",
            'score': 0.9993013,
            'raw_content': None
          },
          {
            'title': 'South Korea GDP Growth Rate 1961-2024 - Macrotrends',
            'url': 'https://www.macrotrends.net/global-metrics/countries/KOR/south-korea/gdp-growth-rate',
            'content': 'South Korea gdp growth rate for 2022 was 2.61%, a 1.69% decline from 2021. South Korea gdp growth rate for 2021 was (생략)...',
            'score': 0.9991272,
            'raw_content': None
          },
          {
            'title': "South Korea's GDP growth hit 11-year high in 2021 as exports boom",
            'url': 'https://www.cnbc.com/2022/01/25/south-koreas-gdp-growth-hit-11-year-high-in-2021-as-exports-boom.html',
            'content': "Tuesday's data from the Bank of Korea showed gross domestic product expanded 4.0% in 2021, as demand for exports soared.",
            'score': 0.997399,
            'raw_content': None
          }
        ],
        'response_time': 2.31
      }
      ),
      ToolMessage(content=
      '[{"url": "https://countryeconomy.com/gdp/south-korea?year=2020", "content": "The GDP per capita of South Korea in 2020 was (생략)..."}]',
      name=
      'tavily_search_results_json',
      tool_call_id=
      'call_V900ERmp5PfXlnBdUS1Ms4iN',
      artifact=
      {
        'query': 'South Korea GDP 2020',
        'follow_up_questions': None,
        'answer': None,
        'images': [],
        'results': [
          {
            'title': 'South Korea GDP - Gross Domestic Product 2020 - countryeconomy.com',
            'url': 'https://countryeconomy.com/gdp/south-korea?year=2020',
            'content': 'The GDP per capita of South Korea in 2020 was €29,487 $31,727, €726 $202 less than in 2019, (생략)...',
            'score': 0.9996288,
            'raw_content': None
          },
          {
            'title': 'South Korea GDP 1960-2024 - Macrotrends',
            'url': 'https://www.macrotrends.net/global-metrics/countries/KOR/south-korea/gdp-gross-domestic-product',
            'content': 'South Korea gdp for 2021 was $1,818.43B, a 10.59% increase from 2020. South Korea gdp for 2020 was (생략)...',
            'score': 0.9983059,
            'raw_content': None
          },
          {
            'title': "South Korea Real Gross Domestic Product - Moody's Analytics",
            'url': 'https://www.economy.com/south-korea/real-gross-domestic-product',
            'content': 'Real Gross Domestic Product for South Korea from The Bank of Korea for the Korean National Accounts [GDP, QNA] release. (생략)...',
            'score': 0.998259,
            'raw_content': None
          },
          {
            'title': '2020 world GDP rankings: South Korea included in top 10 over Russia ...',
            'url': 'https://www.koreatimes.co.kr/www/nation/2021/03/488_305519.html?fl',
            'content': "South Korea's economy is estimated to have ranked 10th in the world in 2020 despite (생략)...",
            'score': 0.9968149,
            'raw_content': None
          },
          {
            'title': 'South Korea GDP Growth Rate 1961-2024 - Macrotrends',
            'url': 'https://www.macrotrends.net/global-metrics/countries/KOR/south-korea/gdp-growth-rate',
            'content': 'South Korea gdp growth rate for 2023 was 1.36%, a 1.26% decline from 2022. (생략)... ...',
            'score': 0.9952448,
            'raw_content': None
          }
        ],
        'response_time': 2.47
      }
      ),
      ToolMessage(content=
      '[{"url": "https://countryeconomy.com/gdp/south-korea?year=2019", "content": "Gross Domestic Product of South Korea grew 2.2% in 2019 .."}]',
      name=
      'tavily_search_results_json',
      tool_call_id=
      'call_hHdg2nLpfcPPM420iWRNHgMA',
      artifact=
      {
        'query': 'South Korea GDP 2019',
        'follow_up_questions': None,
        'answer': None,
        'images': [],
        'results': [
          {
            'title': 'South Korea GDP - Gross Domestic Product 2019 - countryeconomy.com',
            'url': 'https://countryeconomy.com/gdp/south-korea?year=2019',
            'content': 'Gross Domestic Product of South Korea grew 2.2% in 2019 compared to last year. This rate is 7 - (생략)..',
            'score': 0.9997063,
            'raw_content': None
          },
          {
            'title': 'South Korea GDP - TRADING ECONOMICS',
            'url': 'https://tradingeconomics.com/south-korea/gdp',
            'content': 'South Korea GDP Interest Rate South Korea GDP The Gross Domestic Product (GDP) in South Korea was worth (생략)...',
            'score': 0.9899476,
            'raw_content': None
          },
          {
            'title': 'Key economic indicators of South Korea - statistics & facts',
            'url': 'https://www.statista.com/topics/12529/key-economic-indicators-of-south-korea/',
            'content': 'Year-on-year monthly inflation rate South Korea 2019-2024 Unemployment rate 2.7% Detailed statistics (생략)... ..',
            'score': 0.98926485,
            'raw_content': None
          },
          {
            'title': 'South Korea GDP 1960-2024 - Macrotrends',
            'url': 'https://www.macrotrends.net/global-metrics/countries/KOR/south-korea/gdp-gross-domestic-product',
            'content': "South Korea gdp for 2023 was $1,712.79B, a 2.32% increase from 2022. South Korea gdp for 2022 (생략)...",
            'score': 0.9811307,
            'raw_content': None
          },
          {
            'title': 'South Korea GDP Growth Rate 1961-2024 - Macrotrends',
            'url': 'https://www.macrotrends.net/global-metrics/countries/KOR/south-korea/gdp-growth-rate',
            'content': 'South Korea gdp growth rate for 2023 was 1.36%, a 1.26% decline from 2022. South Korea gdp growth rate for 2022 (생략)....',
            'score': 0.9608783,
            'raw_content': None
          }
        ],
        'response_time': 2.11
      }
      )
    ]
  }
}
----
{
  'Researcher': {
    'messages': [
      AIMessage(content=
      'Here is the GDP data for South Korea over the past five years:\n\n- **2018**: $2,053.68 billion\n- **2019**: $1,651.01 billion\n- **2020**: $1,644.31 billion\n- **2021**: $1,818.43 billion\n- **2022**: $1,673.92 billion\n\nNow, I"ll proceed to create a line graph using this data.',
      additional_kwargs=
      {
        'refusal': None
      },
      response_metadata=
      {
        'token_usage': {
          'completion_tokens': 104,
          'prompt_tokens': 4273,
          'total_tokens': 4377,
          'completion_tokens_details': {
            'accepted_prediction_tokens': 0,
            'audio_tokens': 0,
            'reasoning_tokens': 0,
            'rejected_prediction_tokens': 0
          },
          'prompt_tokens_details': {
            'audio_tokens': 0,
            'cached_tokens': 0
          }
        },
        'model_name': 'gpt-4o-2024-08-06',
        'system_fingerprint': 'fp_7f6be3efb0',
        'finish_reason': 'stop',
        'logprobs': None
      },
      name=
      'Researcher',
      id=
      'run-37eeb1c9-6b13-49cd-a248-f1de96f01f9a-0',
      usage_metadata=
      {
        'input_tokens': 4273,
        'output_tokens': 104,
        'total_tokens': 4377,
        'input_token_details': {
          'audio': 0,
          'cache_read': 0
        },
        'output_token_details': {
          'audio': 0,
          'reasoning': 0
        }
      }
      )
    ],
    'sender': 'Researcher'
  }
}
----
{
  'chart_generator': {
    'messages': [
      AIMessage(content=
      '',
      additional_kwargs=
      {
        'tool_calls': [
          {
            'id': 'call_TdrIOgxHn2TcUeaCQFcj3T5R',
            'function': {
              'arguments': '{"code":"import matplotlib.pyplot as plt\\n\\n# GDP data for South Korea\\nyears = [2019, 2020, 2021, 2022, 2023]\\ngdp_values = [1651.01, 1644.31, 1818.43, 1673.92, 1712.79]  # in billions USD\\n\\n# Create a line graph\\nplt.figure(figsize=(10, 6))\\nplt.plot(years, gdp_values, marker=\'o\', linestyle=\'-\', color=\'b\')\\nplt.title(\'South Korea GDP (2019-2023)\')\\nplt.xlabel(\'Year\')\\nplt.ylabel(\'GDP in Billion USD\')\\nplt.xticks(years)\\nplt.grid(True)\\nplt.tight_layout()\\nplt.show()"}',
              'name': 'python_repl'
            },
            'type': 'function'
          }
        ],
        'refusal': None
      },
      response_metadata=
      {
        'token_usage': {
          'completion_tokens': 183,
          'prompt_tokens': 4385,
          'total_tokens': 4568,
          'completion_tokens_details': {
            'accepted_prediction_tokens': 0,
            'audio_tokens': 0,
            'reasoning_tokens': 0,
            'rejected_prediction_tokens': 0
          },
          'prompt_tokens_details': {
            'audio_tokens': 0,
            'cached_tokens': 0
          }
        },
        'model_name': 'gpt-4o-2024-08-06',
        'system_fingerprint': 'fp_7f6be3efb0',
        'finish_reason': 'tool_calls',
        'logprobs': None
      },
      name=
      'chart_generator',
      id=
      'run-5d91429f-8c41-49dc-b94b-3bbd87e97cdc-0',
      tool_calls=
      [
        {
          'name': 'python_repl',
          'args': {
            'code': "import matplotlib.pyplot as plt\n\n# GDP data for South Korea\nyears = [2019, 2020, 2021, 2022, 2023]\ngdp_values = [1651.01, 1644.31, 1818.43, 1673.92, 1712.79]  # in billions USD\n\n# Create a line graph\nplt.figure(figsize=(10, 6))\nplt.plot(years, gdp_values, marker='o', linestyle='-', color='b')\nplt.title('South Korea GDP (2019-2023)')\nplt.xlabel('Year')\nplt.ylabel('GDP in Billion USD')\nplt.xticks(years)\nplt.grid(True)\nplt.tight_layout()\nplt.show()"
          },
          'id': 'call_TdrIOgxHn2TcUeaCQFcj3T5R',
          'type': 'tool_call'
        }
      ],
      usage_metadata=
      {
        'input_tokens': 4385,
        'output_tokens': 183,
        'total_tokens': 4568,
        'input_token_details': {
          'audio': 0,
          'cache_read': 0
        },
        'output_token_details': {
          'audio': 0,
          'reasoning': 0
        }
      }
      )
    ],
    'sender': 'chart_generator'
  }
}
----

실행결과를 확인해보면 아래와 같이 동작한다.

  1. [Researcher] 2019년 ~ 2023년까지 한국의 GDP 검색
  2. call_tool 실행 - 2023년 한국 GDP 검색 (결과 5건)
  3. call_tool 실행 - 2022년 한국 GDP 검색 (결과 5건)
  4. call_tool 실행 - 2021년 한국 GDP 검색 (결과 5건)
  5. call_tool 실행 - 2020년 한국 GDP 검색 (결과 5건)
  6. call_tool 실행 - 2019년 한국 GDP 검색 (결과 5건)
  7. [Research] 과거 5년동안의 GDP의 데이터를 주면서 line graph를 그리는 것을 진행한다.
  8. [chart generator] matplotlib.pyplot을 사용하여 graph 생성 코드를 작성 후 python_repl을 실행한다.
반응형
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유