Use Python to call ChatGPT API

Use Python to call ChatGPT API

ChatGPT is a chat interface based on OpenAI's GPT model. It can be used to build natural language processing applications such as chatbots and intelligent assistants. This article will introduce how to use Python to call ChatGPT API, and show some sample code.

pay attention

  1. GPT will prohibit domestic IP access, so the network environment where the code is running must be non-mainland. It has been tested in Hong Kong, and some foreign regions are not supported.
  2. The answers you want are in the code and comments, very detailed and clear

Preparation

Before starting, you need to complete the following preparations:

  1. Register an OpenAI account: Visit the OpenAI official website openai.com, register an account and log in.

  2. Create an API key: Log in to the OpenAI backend, go to the "API Keys" page, where you can create a new API key.

  3. Install the OpenAI Python library: Open a terminal or command prompt and run the following command to install the OpenAI Python library:

pip install openai
  1. Get the API key: In the Python code, you need to pass the API key of the OpenAI account to the OpenAI library as an environment variable. You can set environment variables by running the following command in Terminal or Command Prompt:
export OPENAI_API_KEY='your-api-key'

Call ChatGPT API

The following is a sample code that uses Python to call ChatGPT API:

import openai

# 设置API密钥
openai.api_key = 'your-api-key'

# 调用ChatGPT API
response = openai.Completion.create(
        model="gpt-3.5-turbo",# 还有其他模型如:gpt-3.5-turbo-16k(支持更大输入输出文本)、gpt-4(账号需要付款1美刀以上解锁)、gpt-4-32k(支持更大文本,一般用户无法使用)
        messages=[{
    
     role: 'system', content: '你是一个数学老师',{
    
     role: 'user', content: '你好,1+1等于几?' }],# role参数有三个选项system(系统设定,赋予gpt一个角色)、user(代表用户也就是你)、assistant(代表gpt),content就是文本内容了,需要联系上下文的话,把前面的历史对话都添加进入到这个数字里即可,这样GPT就能关联上下文了!
        temperature=0.8,# 取值在0-2,值越低回答越死板较为官方标准,值越高回答越随机,答案可能会很离谱荒谬
        stream=false, # 是否采用流文本传输,false的话GPT会一次性把回复内容全部发给你,等待的时间会比较长,响应数据里面会包含输入tokens数和输出tokens数;true的话GPT就会一个一个字的回复给你,需要多次接收,搞起来稍微麻烦一点,这样也能实现像官网那样的打字回复效果,但是响应数据里面不会包含输入tokens数和输出tokens数,这样就需要你利用tiktoken这个库去实现自己计算tokens的消耗了。
)

# 输出响应
print(response.choices[0].text.strip())

# 若需长期使用chatgpt需要必备三样东西:
#1. 魔法梯子
#2. 国外手机号接验证码注册
#3. 国外信用卡(这个最难)

#如果不想这么麻烦的话,这里有一个国内镜像可长期免费使用:chatgpt.indexls.com

In the above code, we openai.api_keypass the API key to the OpenAI library by setting a variable. Then, we called openai.Completion.createthe function to send a chat request. In this request, we specified parameters such as ChatGPT's model engine, chat prompts, and the maximum number of tokens generated. Finally, we print out the response result of the API.

Guess you like

Origin blog.csdn.net/weixin_50814640/article/details/132392298