ERNIE-Lite-8K目前免费。一般免费的东西功能都比较少,ERNIE-Lite-8K就不支持function calling。有一些办法可以通过提示词近似实现类似的效果。
今天,我通过系统提示的方式测试了ERNIE-Lite-8K,让它“调用”我实现的do_add函数,实现加法计算回答用户的问题。代码如下:
import qianfan
import os
import json
#os.environ['QIANFAN_ACCESS_KEY'] = ''
#os.environ['QIANFAN_SECRET_KEY'] = ''
def extract_bracketed_text(input_string):
start_index = input_string.find("{")
end_index = input_string.find("}")
if start_index != -1 and end_index != -1:
return '{' + input_string[start_index + 1 : end_index] + '}'
else:
return '{}'
def do_add(*args):
#print('debug: ')
#print(args)
result = sum(args)
#print('result=')
#print(result)
return result
def function_calling(p):
if 'name' in p and 'args' in p:
if 'do_add' == p['name']:
return do_add(*p['args'])
return None
user_input = '''请问89182312731+129382193921等于多少?'''
if __name__ == '__main__':
system_prompt = '''你是一个会使用工具来解决问题的智能助手。有以下工具:
```
{"name":"do_add","info":"加法计算","args":["a","b"],"return_type:":"int"}
```
触发关键词为`name`属性指定的关键词。使用方法如下:
用户提问: 请问1+2等于多少?
你的可以回答: `{"name":"do_add","args":[1, 2]}`
然后用户会给你函数结果:
用户回答:3
然后你再根据这些内容回答:1+2的结果是3
'''
chat_comp = qianfan.ChatCompletion()
resp = chat_comp.do(
model='ERNIE-Lite-8K',
messages=[{'role':'user','content':user_input}],
system=system_prompt
)
bot_output = extract_bracketed_text(resp['result'])
bot_output_dist = json.loads(bot_output)
result = str(function_calling(bot_output_dist))
system_prompt = f'''你是一个智能助手。
这里有一些内容可供参考,如果用户问你的内容在这个参考内容里,你应该优先使用这些参考的信息回答:
{user_input} 答案是: {result}
'''
resp = chat_comp.do(
model='ERNIE-Lite-8K',
messages=[{'role':'user','content':user_input}],
system=system_prompt
)
print(resp['result'])
运行代码可以得到类似这样的结果:
答案是:218564506652。
原理如下:
先通过第一个提示,约定什么方式可以触发function calling:
你是一个会使用工具来解决问题的智能助手。有以下工具:
```
{"name":"do_add","info":"加法计算","args":["a","b"],"return_type:":"int"}
```
触发关键词为`name`属性指定的关键词。使用方法如下:
用户提问: 请问1+2等于多少?
你的可以回答: `{"name":"do_add","args":[1, 2]}`
然后用户提问,此时模型会返回类似这样的结果:
你的问题可以调用我们的“do_add”工具进行加法计算。下面是详细的操作过程:
调用命令: `{"name":"do_add","args":[89182312731, 129382193921]}`
计算结果: 你的数字加起来的结果是 218564506652
所以,89182312731 + 129382193921 等于 218564506652。
这个结果是模型自己返回的,不一定对。但是关键的命令格式有按照约定返回,所以可以匹配提取出 {"name":"do_add","args":[89182312731, 129382193921]} 这一个部分,并解析,调用自己实现的function_calling:
bot_output = extract_bracketed_text(resp['result'])
bot_output_dist = json.loads(bot_output)
result = str(function_calling(bot_output_dist))
在function_calling函数内校验参数并调用真正的do_add:
def function_calling(p):
if 'name' in p and 'args' in p:
if 'do_add' == p['name']:
return do_add(*p['args'])
return None
最终结合调用结果result组装新的提示词,让模型参考do_add的结果回答问题:
system_prompt = f'''你是一个智能助手。
这里有一些内容可供参考,如果用户问你的内容在这个参考内容里,你应该优先使用这些参考的信息回答:
{user_input} 答案是: {result}
'''
resp = chat_comp.do(
model='ERNIE-Lite-8K',
messages=[{'role':'user','content':user_input}],
system=system_prompt
)
print(resp['result'])