Python日常小操作:chat-gpt-api

  • 前言
  • 前提条件
  • 相关介绍
  • 实验环境
  • 调用方法
    • 安装所需的库
    • API Key and model
    • 运行API
    • 人机对话

前言

  • 由于水平有限,难免出现错漏,敬请批评改正。
  • 更多精彩内容,可点击进入Python日常小操作专栏或我的个人主页查看

前提条件

  • 熟悉Python

相关介绍

  • Python是一种跨平台的计算机程序设计语言。是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越多被用于独立的、大型项目的开发。

实验环境

  • Python 3.x (面向对象的高级语言)

调用方法

安装所需的库

pip install openai
Collecting openai
  Downloading openai-0.26.5.tar.gz (55 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 55.5/55.5 kB 625.2 kB/s eta 0:00:00a 0:00:01
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Installing backend dependencies ... done
  Preparing metadata (pyproject.toml) ... done
Requirement already satisfied: requests>=2.20 in /opt/conda/lib/python3.7/site-packages (from openai) (2.28.1)
Requirement already satisfied: typing-extensions in /opt/conda/lib/python3.7/site-packages (from openai) (4.4.0)
Requirement already satisfied: aiohttp in /opt/conda/lib/python3.7/site-packages (from openai) (3.8.1)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from openai) (4.64.0)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.20->openai) (2022.9.24)
Requirement already satisfied: idna<4,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.20->openai) (3.3)
Requirement already satisfied: charset-normalizer<3,>=2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.20->openai) (2.1.0)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.20->openai) (1.26.12)
Requirement already satisfied: yarl<2.0,>=1.0 in /opt/conda/lib/python3.7/site-packages (from aiohttp->openai) (1.7.2)
Requirement already satisfied: attrs>=17.3.0 in /opt/conda/lib/python3.7/site-packages (from aiohttp->openai) (21.4.0)
Requirement already satisfied: multidict<7.0,>=4.5 in /opt/conda/lib/python3.7/site-packages (from aiohttp->openai) (6.0.2)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /opt/conda/lib/python3.7/site-packages (from aiohttp->openai) (4.0.2)
Requirement already satisfied: asynctest==0.13.0 in /opt/conda/lib/python3.7/site-packages (from aiohttp->openai) (0.13.0)
Requirement already satisfied: frozenlist>=1.1.1 in /opt/conda/lib/python3.7/site-packages (from aiohttp->openai) (1.3.0)
Requirement already satisfied: aiosignal>=1.1.2 in /opt/conda/lib/python3.7/site-packages (from aiohttp->openai) (1.2.0)
Building wheels for collected packages: openai
  Building wheel for openai (pyproject.toml) ... done
  Created wheel for openai: filename=openai-0.26.5-py3-none-any.whl size=67596 sha256=d573f4dabdd8e01cae8cbc794096e3ab63c2596fade4894a490b4126696d6437
  Stored in directory: /root/.cache/pip/wheels/71/cc/39/e215726261759bc158d31178f0ff0adab8111cc1b1d2806ce4
Successfully built openai
Installing collected packages: openai
Successfully installed openai-0.26.5

API Key and model

  • API密钥获取
    链接:https://beta.openai/account/api-keys
import openai
# API 密钥
openai.api_key = "your secret API Key"
# 模型
# model_engine = "text-davinci-002"
model_engine = "text-davinci-003"

运行API

def _get_ans_from_response(response:openai.openai_object.OpenAIObject) -> str:
    first = dict(response)['choices']
    sec = dict(first[0])
    return sec['text']

def _getter(model_engine:str = model_engine,prompt:str = "") -> str:
    # 将请求发送到API
    response = openai.Completion.create(
                          engine=model_engine,
                          prompt=prompt,
                          max_tokens=2048 # max_tokens=1024
                          )
    return _get_ans_from_response(response)

print(_getter(prompt="IT博客网站排行榜"))
1.CSDN:http://www.csdn/
2.Csdn blog:http://blog.csdn/
3.Vue China:https://cn.vuejs/
4.SegmentFault:https://segmentfault/
5.Stack Overflow:https://stackoverflow/
6.腾讯云开发者文档:https://cloud.tencent/document/
7.GitHub:https://github/
8.开发者头条:https://toutiao.io/
9.W3Cfuns:http://www.w3cfuns/
10.51CTO:http://www.51cto/

人机对话

# 人机实时对话
while True:  
    # 设置模型
    model_engine = "text-davinci-003"
    # 输入内容
    prompt = input('Enter your question: ')

    if 'exit' in prompt or 'quit' in prompt:
        break

    # 将请求发送到API
    completion = openai.Completion.create(
        engine=model_engine,
        prompt=prompt,
        max_tokens = 2048, # max_tokens=1024,
        n=3, # n=1,
        stop=None,
        temperature=0.5,
    )
    
    # 提取回答内容
    response = completion.choices[0].text

    # 输出回答内容
    print(response)
Enter your question:  CSDN是什么?

CSDN(China Software Developer Network)是中国最大的IT社区和服务平台,提供最新的技术资讯、IT技术教程、IT资源下载等服务。它致力于为软件开发者提供最新的技术资讯、技术教程、开发经验和代码片段等,帮助开发者提高开发效率和质量。
Enter your question:  用Python写一个冒泡排序。

def bubble_sort(list):
    for i in range(len(list)-1):
        for j in range(len(list)-i-1):
            if list[j] > list[j+1]:
                list[j], list[j+1] = list[j+1], list[j]
    return list

list = [4,2,5,1,3]
print(bubble_sort(list))
Enter your question:  exit

更多精彩内容,可点击进入Python日常小操作专栏或我的个人主页查看

更多推荐

Python日常小操作:chat-gpt-api