51 lines
1.0 KiB
Python
51 lines
1.0 KiB
Python
|
|
from langchain.agents import initialize_agent, AgentType
|
|||
|
|
from langchain_openai import ChatOpenAI
|
|||
|
|
from langchain_core.tools import tool
|
|||
|
|
|
|||
|
|
from conf import settings
|
|||
|
|
|
|||
|
|
|
|||
|
|
# todo: 第一步:定义工具函数
|
|||
|
|
@tool
|
|||
|
|
def add(a: int, b: int) -> int:
|
|||
|
|
"""
|
|||
|
|
将数字a与数字b相加
|
|||
|
|
Args:
|
|||
|
|
a: 第一个数字
|
|||
|
|
b: 第二个数字
|
|||
|
|
"""
|
|||
|
|
return a + b
|
|||
|
|
|
|||
|
|
@tool
|
|||
|
|
def multiply(a: int, b: int) -> int:
|
|||
|
|
"""
|
|||
|
|
将数字a与数字b相乘
|
|||
|
|
Args:
|
|||
|
|
a: 第一个数字
|
|||
|
|
b: 第二个数字
|
|||
|
|
"""
|
|||
|
|
return a * b
|
|||
|
|
|
|||
|
|
# 加载工具
|
|||
|
|
tools = [add, multiply]
|
|||
|
|
|
|||
|
|
# todo: 第二步:初始化模型
|
|||
|
|
llm = ChatOpenAI(
|
|||
|
|
base_url=settings.base_url,
|
|||
|
|
api_key=settings.api_key,
|
|||
|
|
model=settings.model_name,
|
|||
|
|
temperature=0.1
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# todo: 第三步:创建Agent
|
|||
|
|
agent = initialize_agent(
|
|||
|
|
tools,
|
|||
|
|
llm,
|
|||
|
|
AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
|
|||
|
|
verbose=True
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# todo: 第四步:调用Agent
|
|||
|
|
query = "2+1等于多少?"
|
|||
|
|
result = agent.invoke(query)
|
|||
|
|
print(f'result: {result["output"]}')
|