LangChain Agent를 활용한 버스조회

저번 주제와 마찬가지로 Agent의 function calling기능을 사용해보자

  1. 목소리 인증(저번 포스트)

  2. 버스 조회


# 필요 함수 정의
@tool
def search_bus(depart_bus: str, arrival_bus: str, depart_date: str) -> dict:
셀레니움을 통한 버스예매
...

@tool
def get_voice_and_verify():
...


def main():
    model = ChatOpenAI(model="gpt-4o", openai_api_key=OPENAI_API_KEY)
    prompt = ChatPromptTemplate.from_messages([
        ('system', '너는 유용한 인공지능 조수야'),
        ("placeholder", "{chat_history}"),
        ("human", "{input}"),
        ("placeholder", "{agent_scratchpad}"),
    ])

    tools = [get_voice_and_verify, search_bus]
    agent = create_tool_calling_agent(model, tools, prompt)
    agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
    
    chat_history = []

    while True:
        input_text = input("궁금한걸 물어보세요:")
        if input_text=='exit':break

        chat_history.append(HumanMessage(content=input_text))

        ans = agent_executor.invoke(
            {
                "input": input_text,
                "chat_history": chat_history,
            }
        )

        chat_history.append(AIMessage(content=ans['output']))
        print(f"에이전트: {ans}")
    print('종료합니다.')

코드 실행


## 실행 결과 ## 
~/gpters  python function_calling.py
궁금한걸 물어보세요:동서울에서 출발해서 가평가는  2024-07-08버스에 대해서 알려줘


> Entering new AgentExecutor chain...

Invoking: `search_bus` with `{'depart_bus': '동서울', 'arrival_bus': '가평', 'depart_date': '2024-07-08'}`


[{'bus_id': 0, 'depart_time': '06:45', 'price': '8000'}, {'bus_id': 1, 'depart_time': '09:15', 'price': '8000'}, {'bus_id': 2, 'depart_time': '11:40', 'price': '8000'}]2024년 7월 8일에 동서울에서 가평으로 가는 버스 정보는 다음과 같습니다:

1. **출발 시간: 06:45** - 가격: 8,000원
2. **출발 시간: 09:15** - 가격: 8,000원
3. **출발 시간: 11:40** - 가격: 8,000원

필요한 시간이 있으면 말씀해 주세요!

> Finished chain.
에이전트: {'input': '동서울에서 출발해서 가평가는 2024-07-08버스에 대해서 알려줘', 'chat_history': [HumanMessage(content='동서울에서 출발해서 가평가는 2024-07-08버스에 대해서 알려줘'), AIMessage(content='2024년 7월 8일에 동서울에서 가평으로 가는 버스 정보는 다음과 같습니다:\n\n1. **출발 시간: 06:45** - 가격: 8,000원\n2. **출발 시간: 09:15** - 가격: 8,000원\n3. **출발 시간: 11:40** - 가격: 8,000원\n\n필요한 시간이 있으면 말씀해 주세요!')], 'output': '2024년 7월 8일에 동서울에서 가평으로 가는 버스 정보는 다음과 같습니다:\n\n1. **출발 시간: 06:45** - 가격: 8,000원\n2. **출발 시간: 09:15** - 가격: 8,000원\n3. **출발 시간: 11:40** - 가격: 8,000원\n\n필요한 시간이 있으면 말씀해 주세요!'}
궁금한걸 물어보세요:좋아 구 저장된 목소리와 내 목소리가 같다면 구매를 진행하고싶어 저장된 목소리와  비교해줘


> Entering new AgentExecutor chain...

Invoking: `get_voice_and_verify` with `{}`


녹음 시작...
녹음 완료!
Similarity: 0.48654231429100037
(True, 0.48654231429100037)목소리 인증이 성공적으로 완료되었습니다. (유사도 점수: 0.49)

이제 2024년 7월 8일에 동서울에서 가평으로 가는 버스를 구매하도록 하겠습니다. 선택하실 출발 시간을 알려주세요. 현재 가능한 시간은 다음과 같습니다:

1. **출발 시간: 06:45** - 가격: 8,000원
2. **출발 시간: 09:15** - 가격: 8,000원
3. **출발 시간: 11:40** - 가격: 8,000원


openai의 function calling을 직접 정의하는 것 보다 훨씬 간편하고 유용하다.

5

👉 이 게시글도 읽어보세요