安装依赖
pip install -qU langchain-core langchain-openai
编写代码
定义一个工具
# 定义工具
@tool
def get_word_length(word: str) -> int:
"""Returns the length of a word."""
return len(word)
创建一个Agent
# 创建Agent
agent = (
{
"input": lambda x: x["input"],
"agent_scratchpad": lambda x: format_to_openai_tool_messages(
x["intermediate_steps"]
),
}
| prompt
| llm_with_tools
| OpenAIToolsAgentOutputParser()
)
推荐使用GPT-4
,GPT3.5
任务表现上并不是很好。
完整的代码如下
from langchain_openai import ChatOpenAI
from langchain.agents import tool
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.agents.format_scratchpad.openai_tools import (
format_to_openai_tool_messages,
)
from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParser
from langchain.agents import AgentExecutor
llm = ChatOpenAI(model="gpt-4-turbo-preview", temperature=0)
# llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
# 定义工具
@tool
def get_word_length(word: str) -> int:
"""Returns the length of a word."""
return len(word)
# print(get_word_length.invoke("abc"))
# 定义一个工具集
tools = [get_word_length]
# 提示词
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are very powerful assistant, but don't know current events",
),
(
"user",
"{input}"
),
MessagesPlaceholder(variable_name="agent_scratchpad"),
]
)
# 绑定工具集
llm_with_tools = llm.bind_tools(tools)
# 创建Agent
agent = (
{
"input": lambda x: x["input"],
"agent_scratchpad": lambda x: format_to_openai_tool_messages(
x["intermediate_steps"]
),
}
| prompt
| llm_with_tools
| OpenAIToolsAgentOutputParser()
)
# 执行器
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor_stream = list(agent_executor.stream({"input": "How many letters in the word eudca"}))
print(f"agent_executor_stream: {agent_executor_stream}")
执行结果
➜ python3 test27.py
> Entering new AgentExecutor chain...
Invoking: `get_word_length` with `{'word': 'eudca'}`
5The word "eudca" has 5 letters.
> Finished chain.
agent_executor_stream: [{'actions': [OpenAIToolAgentAction(tool='get_word_length', tool_input={'word': 'eudca'}, log="\nInvoking: `get_word_length` with `{'word': 'eudca'}`\n\n\n", message_log=[AIMessageChunk(content='', additional_kwargs={'tool_calls': [{'index': 0, 'id': 'call_Oo2mhYvyOHkw4YvzaL1Gz0tb', 'function': {'arguments': '{"word":"eudca"}', 'name': 'get_word_length'}, 'type': 'function'}]}, response_metadata={'finish_reason': 'tool_calls'})], tool_call_id='call_Oo2mhYvyOHkw4YvzaL1Gz0tb')], 'messages': [AIMessageChunk(content='', additional_kwargs={'tool_calls': [{'index': 0, 'id': 'call_Oo2mhYvyOHkw4YvzaL1Gz0tb', 'function': {'arguments': '{"word":"eudca"}', 'name': 'get_word_length'}, 'type': 'function'}]}, response_metadata={'finish_reason': 'tool_calls'})]}, {'steps': [AgentStep(action=OpenAIToolAgentAction(tool='get_word_length', tool_input={'word': 'eudca'}, log="\nInvoking: `get_word_length` with `{'word': 'eudca'}`\n\n\n", message_log=[AIMessageChunk(content='', additional_kwargs={'tool_calls': [{'index': 0, 'id': 'call_Oo2mhYvyOHkw4YvzaL1Gz0tb', 'function': {'arguments': '{"word":"eudca"}', 'name': 'get_word_length'}, 'type': 'function'}]}, response_metadata={'finish_reason': 'tool_calls'})], tool_call_id='call_Oo2mhYvyOHkw4YvzaL1Gz0tb'), observation=5)], 'messages': [FunctionMessage(content='5', name='get_word_length')]}, {'output': 'The word "eudca" has 5 letters.', 'messages': [AIMessage(content='The word "eudca" has 5 letters.')]}]