Python的requests库调用gpt3.5
1. 注册ChatGPT API,放到变量key里
2. 安装requests库
3. 发送API请求
4. 其他API调用方式
-除了使用Python库进行API调用之外,你还可以使用其他编程语言或命令行工具进行API调用。具体的调用方式可以参考ChatGPT官方文档中的API参考。
import requests def gpt_res(content, apikey): url = "https://api.openai.com/v1/chat/completions" if not content: return datas = { "model": "gpt-3.5-turbo", "messages": content, "temperature": 0.5, "presence_penalty": 0, "stream": False, } headers = { "Content-Type": "application/json", "Authorization": "Bearer " + apikey } response = requests.post(url=url, headers=headers, json=datas, verify=False) return response if __name__ == '__main__': key = "fk-xxxx-xxx" user_input = [ { "role": "system", "content": "you are a helpful assistant that translates English to Chinese" }, # 设置系统角色 { "role": "user", "content": "hi" }, # 设置用户示例 { "role": "assistant", "content": "你好" }, # 设置机器人示例 { "role": "user", "content": "Your trusted source for Canadian drug information" }, # 用户问问题 ] r = gpt_res(user_input, key) try: # print(r.json()) print(r.json()["choices"][0]["message"]["content"]) except KeyError: print(r.json()["error"])