最近openai推出了新的模型,以及chat接口加了新的function_call方法。分享一段在项目中使用的例子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def get_messages_keyword(self):
completion = openai.ChatCompletion.create(model="gpt-3.5-turbo-16k", messages=self.messages,
functions=[
{
"name": "search_references",
"description": "search in the database or google for references that might be helpful in answering this question",
"parameters": {
"type": "object",
"properties": {
"keyword": {
"type": "string",
"description": "The search keyword"
}
},
"required": ["keyword"]
}
}
],
function_call={"name": 'search_references'},
temperature=0, presence_penalty=-2)

return json.loads(completion.choices[0]['message']['function_call']['arguments'])['keyword']

这样在回答问题之前,能得到需要搜索的关键词,去数据库和互联网搜索相关参考,然后拼接到messages里面作为辅助信息,实现GPT的联网功能,以及记忆搜索功能。