当前位置:   article > 正文

使用API调用ChatGPT_apifox 调用chatgpt4

apifox 调用chatgpt4

前提条件:

1. 能够科学上网

2. 在openai官网注册了账号

1. 获取Access Key

  1. 登录openai官网,查看Access key,地址:openai查看accesskey
  2. 创建好后复制AccessKey,将其保存(如果后面再想查看这个key,会发现key的信息被隐藏掉了,所以创建好后就及时保存)
  3. 准备工作已完成,下面提供两个文档:
    1. 聊天API简介:https://platform.openai.com/docs/guides/gpt/chat-completions-api
    2. 详细API参考文档:https://platform.openai.com/docs/guides/gpt/chat-completions-api

2. 使用Python调用GPT

  1. 安装openai的包:
    pip install openai
  2.  运行下列代码:
    1. import openai
    2. openai.api_key = "引号内换成你自己的AccessKey"
    3. response = openai.ChatCompletion.create(
    4. model="gpt-3.5-turbo",
    5. messages=[
    6. {"role": "user", "content": "Where was it played?"}
    7. ]
    8. )
    9. print(response['choices'][0]['message']['content'])
  3. 运行结果如下:
  4. 在首次运行可能会遇到:
    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以下即可,如:

    1. //卸载原有的urllib3
    2. pip uninstall urllib3
    3. //安装指定版本
    4. pip install urllib3==1.25.11
    5. //查看安装好的urllib3的版本
    6. pip list

    更换好版本之后如果还报错请仔细检查是否有科学上网

3. 请求和相应解析

请求参数:

请求参数有很多,其中必须的两个是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

返回参数:

  1. {
  2. "id": "chatcmpl-123",
  3. "object": "chat.completion",
  4. "created": 1677652288,
  5. "model": "gpt-3.5-turbo-0613",
  6. "choices": [{
  7. "index": 0,
  8. "message": {
  9. "role": "assistant",
  10. "content": "\n\nHello there, how may I assist you today?",
  11. },
  12. "finish_reason": "stop"
  13. }],
  14. "usage": {
  15. "prompt_tokens": 9,
  16. "completion_tokens": 12,
  17. "total_tokens": 21
  18. }
  19. }

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号