通过modelscope-agent做了个demo,写了tool调用成功了,怎么让modelscope的tool内的一个参数每次都需要经过用户对话确认或者补充后再继续进行?
要实现让 modelscope
的工具(tool)内的某个参数每次都需要经过用户对话确认或补充后再继续进行,可以通过以下方法实现。这种方法的核心是利用 Function Calling 的交互机制,结合对话历史和用户输入来动态调整工具调用的参数。
首先,确保你的工具函数定义中包含需要用户确认或补充的参数。例如,假设你有一个工具函数 get_weather
,其参数为 location
,而这个参数需要用户确认或补充:
{
"name": "get_weather",
"description": "获取指定城市的天气信息。",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "需要查询天气的城市名称。"
}
},
"required": ["location"]
}
}
在调用模型时,通过 tool_choice
参数强制指定工具调用策略。例如,你可以设置模型必须调用 get_weather
工具:
response = client.chat.completions.create(
model="qwen-plus",
messages=messages,
tools=[tools], # 工具列表
tool_choice={"type": "function", "function": {"name": "get_weather"}}
)
这一步确保模型会尝试调用 get_weather
工具,但不会直接生成完整的参数值,而是根据上下文生成一个初步的参数值。
当模型生成工具调用请求后,检查生成的参数是否完整或符合预期。如果参数不完整或需要用户确认,则将该参数作为问题返回给用户,并等待用户的进一步输入。
例如,假设模型生成了以下工具调用请求:
{
"function": {
"name": "get_weather",
"arguments": "{\"location\": \"北京\"}"
}
}
此时,你可以通过对话向用户确认或补充参数:
系统:我将为您查询天气,请确认城市名称是否为“北京”?如果不是,请告诉我正确的城市名称。
用户可以回复确认或提供新的城市名称,例如:
用户:不是,应该是“上海”。
然后,将用户的输入更新到工具调用的参数中,重新发起工具调用。
在用户确认或补充参数后,将用户的输入更新到对话历史中,以便模型在后续对话中能够参考这些信息。例如:
messages.append({"role": "user", "content": "不是,应该是‘上海’。"})
messages.append({"role": "assistant", "content": "好的,我将为您查询上海的天气。"})
使用更新后的参数重新调用工具。例如,将 location
参数更新为用户提供的值后,再次调用 get_weather
工具:
response = client.chat.completions.create(
model="qwen-plus",
messages=messages,
tools=[tools],
tool_choice={"type": "function", "function": {"name": "get_weather"}}
)
以下是一个完整的示例代码,展示如何实现上述流程:
from openai import OpenAI
client = OpenAI(api_key="your_api_key")
# 定义工具
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气信息。",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "需要查询天气的城市名称。"
}
},
"required": ["location"]
}
}
}
]
# 初始化对话历史
messages = [{"role": "user", "content": "我想知道天气。"}]
# 第一次调用模型
response = client.chat.completions.create(
model="qwen-plus",
messages=messages,
tools=tools,
tool_choice={"type": "function", "function": {"name": "get_weather"}}
)
# 检查生成的工具调用
tool_call = response.choices[0].message.tool_calls[0]
location = json.loads(tool_call.function.arguments)["location"]
# 向用户确认参数
messages.append({"role": "assistant", "content": f"我将为您查询天气,请确认城市名称是否为“{location}”?如果不是,请告诉我正确的城市名称。"})
# 模拟用户输入
user_input = "不是,应该是‘上海’。"
messages.append({"role": "user", "content": user_input})
# 更新参数并重新调用工具
updated_location = "上海"
tool_call.function.arguments = json.dumps({"location": updated_location})
messages.append({"role": "assistant", "content": f"好的,我将为您查询{updated_location}的天气。"})
# 再次调用模型
response = client.chat.completions.create(
model="qwen-plus",
messages=messages,
tools=tools,
tool_choice={"type": "function", "function": {"name": "get_weather"}}
)
通过上述方法,您可以实现工具参数的动态确认或补充,从而提升用户体验和交互的灵活性。
ModelScope旨在打造下一代开源的模型即服务共享平台,为泛AI开发者提供灵活、易用、低成本的一站式模型服务产品,让模型应用更简单!欢迎加入技术交流群:微信公众号:魔搭ModelScope社区,钉钉群号:44837352