エンジニアリングとお金の話

都内で働くエンジニアの日記です。

langchainのchainとagentの連携について

【SPONSORED LINK】

langchainの勉強の一貫としてchainとagentの連携を行ってみた。

フォルダ構成

langchain_work_3
├── agent.py
├── main.py
├── output_parser.py
└── tools.py

処理内容

  1. main.pyからagent.pyを呼び出す
  2. agent.pyの中で条件を達成するためのツールをtools.pyから選択。tools.pyを使用し必要な値を取得
  3. 2にて取得した値をmain.pyの中でパースし、json形式に変換

※今回tools.pyは日本株価ニュースとアメリカ株価ニュースを文字列で返却
※main.pyからagent.pyを呼び出す際の引数(日本 or アメリカ)で自動的にagent側で使用するツールを判別する

処理結果

Entering new AgentExecutor chain... I need to provide information on Japanese stock market Action: 日本の株式情報 Action Input: None Observation: 日経平均は大幅に3日続伸。2日の米株式市場でダウ平均は701.19ドル高と大幅続伸。財政責任法案が上院で可決、債務不履行(デフォルト)が回避されたことで買いが先行。5月雇用統計は強弱入り混じる内容だったが、今月開催の連邦公開市場委員会(fomc)での利上げ一時停止の予想を変更させるほどの内容ではないとの見方から相場を一段と押し上げた。ナスダック総合指数は+1.06%と続伸。米株高を引き継いで日経平均は339.9円高からスタート。再び140円台に乗せた円安・ドル高や中国による経済政策期待も手伝い、景気敏感株を中心に買いが加速。心理的な節目を前にもみ合う場面もあったが、値がさ株やハイテク株にも買いが入るなか、前場中ごろには32000円を突破。後場は一段と上値を伸ばす展開となり、高値引けとなった。

大引けの日経平均は前日比693.21円高の32217.43円となった。東証プライム市場の売買高は14億7600万株、売買代金は3兆8712億円だった。セクターでは機械、海運、繊維製品が上昇率上位に並んだ一方、電気・ガスのみが下落した。東証プライム市場の値上がり銘柄は全体の89%、対して値下がり銘柄は9%だった。

Thought:I have the information on the Japanese stock market Final Answer: The Nikkei average rose significantly for the third consecutive day, with the Dow Jones Industrial Average rising significantly in the US stock market on the second day. The market was driven by buying after the Fiscal Responsibility Bill was passed in the Senate, avoiding default. The May employment statistics were mixed, but not enough to change expectations of a temporary pause in interest rate hikes at the Federal Open Market Committee (FOMC) meeting this month, pushing the market up further. The Nasdaq Composite Index also continued to rise. The Nikkei average started at 339.9 yen higher, riding on the yen's depreciation and the expectation of China's economic policy. While there were some struggles before the psychological milestone, buying accelerated, especially in cyclical stocks, and the market broke through 32,000 yen in the middle of the morning session. In the afternoon, the market continued to rise, and the closing price was at a high. The Nikkei average at the close was 32,217.43 yen, up 693.21 yen from the previous day. The trading volume on the Tokyo Stock Exchange Prime Market was 1.476 billion shares, with a trading value of 3.8712 trillion yen. In terms of sectors, machinery, shipping, and textile products were among the top gainers, while only electricity and gas declined. The number of rising stocks on the Tokyo Stock Exchange Prime Market was 89% of the total, while the number of declining stocks was 9%.

Finished chain. {"stock": "32,217.43 yen", "late": "693.21 yen"} 想定どおり、日本株の株価と上昇額が取れた

ポイント

  • initialize_agent()でagentインスタンスを作成する時、引数にverbose=Trueを付けると処理内容が詳細に分かりデバックしやすい
  • 処理結果をjson型にするなど指定したい場合はPromptTemplateのpartial_variablesに辞書型で{"format_instructions": info_output_parser.get_format_instructions()}と値を渡す。info_output_parserはpydanticのBaseModelを継承したクラスで型を定義しPydanticOutputParserで取得したインスタンス。

ソース

main.py

from agent import request_agent
from dotenv import load_dotenv
from langchain import PromptTemplate
from langchain.chains import LLMChain
from langchain.chat_models import ChatOpenAI
from output_parser import info_output_parser

load_dotenv()

today_news = request_agent("日本")

template = """
与えた情報から以下を出力して下さい。
{info}
- 株価
- 前日比
\n{format_instructions}
"""

sum_tmplate = PromptTemplate(
    input_variables=["info"],
    template=template,
    partial_variables={"format_instructions": info_output_parser.get_format_instructions()},
)

llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo")

chain = LLMChain(llm=llm, prompt=sum_tmplate)


print(chain.run(info=today_news))

agent.py

from langchain import PromptTemplate
from langchain.agents import AgentType, Tool, initialize_agent
from langchain.chat_models import ChatOpenAI

from langchain_work_3.tools import get_japan_stockt, get_usa_stockt


def request_agent(word: str) -> str:
    template = """
    {word}の株式情報を教えて
    """

    prompt_template = PromptTemplate(template=template, input_variables=["word"])

    llm = ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo")

    tools_for_agent = [
        Tool(
            name="日本の株式情報",
            func=get_japan_stockt,
            description="日本の株式情報をテキストメッセージで返却します",
        ),
        Tool(
            name="アメリカの株式情報",
            func=get_usa_stockt,
            description="アメリカの株式情報をテキストメッセージで返却します",
        ),
    ]

    agent = initialize_agent(tools=tools_for_agent, llm=llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
    return agent.run(prompt_template.format_prompt(word=word))

tools.py

def get_japan_stockt(arg) -> str:
    return """\
日経平均は大幅に3日続伸。2日の米株式市場でダウ平均は701.19ドル高と大幅続伸。財政責任法案が上院で可決、債務不履行(デフォルト)が回避されたことで買いが先行。5月雇用統計は強弱入り混じる内容だったが、今月開催の連邦公開市場委員会(fomc)での利上げ一時停止の予想を変更させるほどの内容ではないとの見方から相場を一段と押し上げた。ナスダック総合指数は+1.06%と続伸。米株高を引き継いで日経平均は339.9円高からスタート。再び140円台に乗せた円安・ドル高や中国による経済政策期待も手伝い、景気敏感株を中心に買いが加速。心理的な節目を前にもみ合う場面もあったが、値がさ株やハイテク株にも買いが入るなか、前場中ごろには32000円を突破。後場は一段と上値を伸ばす展開となり、高値引けとなった。

大引けの日経平均は前日比693.21円高の32217.43円となった。東証プライム市場の売買高は14億7600万株、売買代金は3兆8712億円だった。セクターでは機械、海運、繊維製品が上昇率上位に並んだ一方、電気・ガスのみが下落した。東証プライム市場の値上がり銘柄は全体の89%、対して値下がり銘柄は9%だった。
"""


def get_usa_stockt(arg) -> str:
    return """\
午後3時過ぎにS&P500は前日比+1.65%の4290まで上昇し、高値圏で終了した。ダウ平均が+2.12%、S&P500が+1.45%、ナスダック総合が+1.07%。全11セクターが上昇し、中でも素材が+3.37%、資本財エネルギーが共に+2.96%。個別では、3M(MMM)が水質汚染問題で複数都市と暫定和解に達し+8.75%。ルルレモン・アスレティカ(LULU)が好調なF1Q決算を発表し+11.3%。モンゴーDB(MDB)がF1Q業績の大幅上振れを示し+28.01%。他方、TモバイルUS(TMUS)が上記アマゾン(AMZN)の参入発表を受け-5.56%。センチネルワン(S)がF1Q決算にて実績・ガイダンスが嫌気され-35.14%
"""

output_parser.py

from langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field


class InfoOutput(BaseModel):
    stock: str = Field(description="stock value")
    late: str = Field(description="stock late today")

    def to_dict(self):
        return {"stock": self.stock, "late": self.late}


info_output_parser: PydanticOutputParser = PydanticOutputParser(pydantic_object=InfoOutput)