Agent 与工具调用2012 字
基于LangGraph开发智能收集小助手
·全库 492 / 611
《基于LangGraph开发智能收集小助手》共 0.2 万字,通篇围绕 prompt、工具调用、需求 展开,归在「Agent 与工具调用」这一层。
覆盖prompt工具调用需求
适合要让 AI 真的去干活、不只是陪人聊天的人
目录骨架(1 节)
- 需求智能收集助手
示例代码
注:将ppt后缀名改为zip后解压
python版本:3.12.4
需求智能收集助手
在这个例子中,我们将创建一个帮助用户生成提示的聊天机器人。它将首先从用户那里收集需求,然后生成提示(并根据用户输入进行细化)。这些被分成两个独立的状态,LLM 决定何时在它们之间转换。
下面的图表显示了该系统的图形表示。
收集信息
首先,让我们定义图中用于收集用户需求的部分。这将是一个带有特定系统消息的 LLM 调用。它将访问一个工具,当它准备好生成提示时可以调用该工具。
from typing import List
from langchain_core.messages import SystemMessage
from langchain_core.pydantic_v1 import BaseModel
from langchain_openai import ChatOpenAI
# 定义一个模板字符串,用于指导用户提供创建提示模板所需的信息
template = """Your job is to get information from a user about what type of prompt template they want to create.
You should get the following information from them:
- What the objective of the prompt is
- What variables will be passed into the prompt template
- Any constraints for what the output should NOT do
- Any requirements that the output MUST adhere to
If you are not able to discern this info, ask them to clarify! Do not attempt to wildly guess.
After you are able to discern all the information, call the relevant tool."""
# 定义一个函数,用于将系统消息和用户消息组合成一个消息列表
def get_messages_info(messages):
return [SystemMessage(content=template)] + messages
# 定义一个数据模型,用于存储提示模板的指令信息
class PromptInstructions(BaseModel):
"""Instructions on how to prompt the LLM."""
objective: str
variables: List[str]
constraints: List[str]
requirements: List[str]
# 初始化一个 ChatOpenAI 实例,温度设为 0
llm = ChatOpenAI(temperature=0)
# 将工具绑定到 LLM 实例上
llm_with_tool = llm.bind_tools([PromptInstructions])
# 将消息处理链定义为 get_messages_info 函数和绑定工具的 LLM 实例
chain = get_messages_info | llm_with_tool
生成提示
现在,我们设置一个生成提示的状态。这将需要一个单独的系统消息,以及一个函数来过滤掉在工具调用之前的所有消息(因为那是上一个状态决定是时候生成提示的时候)。
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
# 定义一个新的系统提示模板
prompt_system = """Based on the following requirements, write a good prompt template:
{reqs}"""
# 定义一个函数,用于获取生成提示模板所需的消息
# 只获取工具调用之后的消息
def get_prompt_messages(messages: list):
tool_call = None
other_msgs = []
for m in messages:
if isinstance(m, AIMessage) and m.tool_calls:
tool_call = m.tool_calls[0]["args"]
elif isinstance(m, ToolMessage):
continue
elif tool_call is not None:
other_msgs.append(m)
return [SystemMessage(content=prompt_system.format(reqs=tool_call))] + other_msgs
# 将消息处理链定义为 get_prompt_messages 函数和 LLM 实例
prompt_gen_chain = get_prompt_messages | llm