赞
踩
前提条件:
1. 能够科学上网
2. 在openai官网注册了账号
pip install openai
- import openai
- openai.api_key = "引号内换成你自己的AccessKey"
- response = openai.ChatCompletion.create(
- model="gpt-3.5-turbo",
- messages=[
- {"role": "user", "content": "Where was it played?"}
- ]
- )
- print(response['choices'][0]['message']['content'])
openai.error.APIConnectionError: Error communicating with OpenAI: HTTPSConnectionPool(host=‘api.openai.com’, port=443)
这是因为环境内的urllib3版本是1.26.14版本,urllib3在1.26版本时增加了对HTTPS代理与HTTPS服务器联系的支持,需要将urllib3的版本降低到1.26以下即可,如:
- //卸载原有的urllib3
- pip uninstall urllib3
- //安装指定版本
- pip install urllib3==1.25.11
- //查看安装好的urllib3的版本
- pip list
更换好版本之后如果还报错请仔细检查是否有科学上网
请求参数:
请求参数有很多,其中必须的两个是model和message,其中官网的解释如下:
model:即选用的模型,官网提供的模型有gpt-4, gpt-3.5-turbo,babbage-002, davinci-002,text-davinci-003, text-davinci-002, davinci, curie, babbage, ada等,后面的这些是较早推出的版本,性能和效果不如前面的,所以如果不知道选什么模型就直接选择gpt-3.5-turbo。
messages:消息主题,其类型为列表,列表中每个元素为k-v键值对,其中,role和content是必要的。content即想要向gtp发送的内容主体,role分为四个,system,user,assistant和function,其中user即用户,表示这个消息是由用户发送的;assistant为gpt,表示这个消息是由gpt返回的。
其他参数参考:https://platform.openai.com/docs/api-reference/chat/create
返回参数:
- {
- "id": "chatcmpl-123",
- "object": "chat.completion",
- "created": 1677652288,
- "model": "gpt-3.5-turbo-0613",
- "choices": [{
- "index": 0,
- "message": {
- "role": "assistant",
- "content": "\n\nHello there, how may I assist you today?",
- },
- "finish_reason": "stop"
- }],
- "usage": {
- "prompt_tokens": 9,
- "completion_tokens": 12,
- "total_tokens": 21
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。