autogen function calling
AI 2024/3/13 9:39:41 点击:不统计
<本文原载于www.forasp.cn>
在使用autogen框架作为 ai服务扩展时,有function call的处理,它是怎么做的?
1. 定义函数
比如 def get_sum_args(data):
"""
只有一个参数,以{}dict形式存在,可以时多维数组,或者用于扩展参数
比如:参数{"x":1,"y":2} 返回 和
"""
sum = 0
for item in data.keys():
sum = sum + data[item]
return sum
2. 定义 function 数组记录名称指向
"""
前面时 定义的函数名称,将来用于openai
后面值 定义了函数指向,指向实质的函数
"""
available_function = {
"get_sum_args": get_sum_args,
}
3. 函数字典,每个函数有个字典,定义用于给AI介绍函数信息
# name函数名称,与定义function 数组名称要一致
# description 描述,对该函数的描述,给AI介绍的 的
# parameters 参数,即函数的参数介绍
get_sum_function = {
"name":"get_sum_args",
"description":"介绍该函数",
"parameters": {
"type":"dict",
"properties":{
"x" :{
"type": "number"
},
"y" :{
"type": "number"
}
},
"required":["data"]
}
}
如果时数组类型的
get_sum_function = {
"name":"get_sum_args",
"description":"介绍该函数",
"parameters": {
"type":"array",
"items": {
"type":"dict",
"properties":{
"x" :{
"type": "number"
},
"y" :{
"type": "number"
}
},
"required":["x","y"]
}
}
}
4. AI 实现调用
(1)如何配置function ,这里需要两个agent 比如 userAgent_proxy 和 Assistant_proxy
需要在 userAgent 配置可用调用的函数,available_function 代码如下,定义可用调用函数:
userAgent_proxy = autogen.UserProxyAgent(
name="User_proxy",
system_message="A human admin that will execute function_calls.",
function_map=available_function,
human_input_mode="NEVER",
)
在 Assistant_proxy 中配置,告诉AI 可用调用的方法,下面的 get_sum_args和 介绍该函数和上面定义函数一致。 上面的 get_sum_function 是为了组织文字到下面的 system_message
llm_config 中设置function 告知 ai 调可用调用函数定义
llm_config = {
.....
"functions": get_sum_function,
.....
}
Assistant_proxy = autogen.AssistantAgent(
name="Player",
system_message="You will can function `get_sum_args` to 介绍该函数. Reply TERMINATE to stop.",
llm_config=llm_config,
)
(2) 请求AI,或者agent 之间对话,返回response结果会有
choices:[
{
"finsh_reason": "function_call",
"index": 0,
"message":{
"content":null,
"function_call": {
"name": "get_sum_args",
"arguments": "{\"x\":1,\"y\":2 }"
}
}
}
]
(3)运行function_call
第一种手动运行function call
function_arg = json_load(response["choices"][0]["message"]["function_call"]["arguments"])
call_name = json_load(response["choices"][0]["message"]["function_call"]["name"])
fact_function = available_function[call_name]
function_result = fact_function(function_arg)
然后 将执行的function call 结果追加到message
message.append({
"role":"function",
"name": call_name,
"content": function_result
})
第二种 自动运行function call,通过agent 之间的对话,将 function 定义到返回function_call 消息的下一个agent 上,让agent 自动执行,并追加到
user = UserProxyAgent(name="test", function_map=available_function)
这里的agent中的处理函数generate_function_call_reply 会根据 会话消息调用function call,
<%77w%77%2Ef%6F%72p%73%70%2Ec%6E>
·上一篇:如何本地部署运行GPT >> ·下一篇:LLM 大语言模型的问题 >>