2023-09-26
chatgpt
00
请注意,本文编写于 368 天前,最后修改于 368 天前,其中某些信息可能已经过时。

目录

函数调用 (function calling)
自定义函数
functions格式
程序入口
调用

函数调用 (function calling)

自定义函数

python
def get_text_from_url(url): headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"} response = requests.get(url, headers=headers) html = response.text soup = BeautifulSoup(html, 'html.parser') extracted_tags = soup.find_all(is_target_tag) res_text = '' for tag in extracted_tags: res_text = res_text + tag.get_text(strip=True) + '\n' return res_text

functions格式

按照openai 所需要的格式 编写描述你的方法

functions = [ { "name": "get_text_from_url", "description": "抓取url对应的网页里的文本内容", "parameters": { "type": "object", "properties": { "url": { "type": "string", "description": "网址url", } }, "required": ["url"], }, } ]

程序入口

维护一个可用的function字典

python
available_functions = { "get_text_from_url": get_text_from_url, }
python
def chat2ai(content): messages = [ {"role": "user", "content": content} ] response1 = openai.ChatCompletion.create( model="gpt-3.5-turbo-0613", messages=messages, functions=functions, function_call="auto" ) response_message = response1["choices"][0]["message"] print(response_message) rtn_message = response1["choices"][0]["message"] print(rtn_message) # 如果ChatGPT返回结果会告诉你,是否需要调用函数,我们只需要根据它返回的函数名、参数调起对应的函数 # 然后将函数的返回结果再给到ChatGPT,让他进行下一步的操作 if response_message.get("function_call"): # 找到需要调用的函数,并将ChatGPT给的参数传进去 function_name = response_message["function_call"]["name"] function_to_call = available_functions[function_name] function_args = json.loads(response_message["function_call"]["arguments"]) # 用这种方式可以调起任意python函数,不用像官网那样还要指定参数名 function_response = function_to_call(**function_args) # 获取到函数调用结果后,需要将结果拼接到对话记录里,并再次调用ChatGPT messages.append(response_message) messages.append( { "role": "function", "name": function_name, "content": function_response, } ) print(messages) # 二次调用的返回结果里就是我们预期的结果了 response2 = openai.ChatCompletion.create( model="gpt-3.5-turbo-0613", messages=messages, ) rtn_message = response2["choices"][0]["message"] print(rtn_message) return rtn_message['content']

调用

python
res = chat2ai('总结下这篇文章,将其中的要点提炼出来 https://zxs.io/article/1924') print(res)
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:李佳玮

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!