OpenAI API 入门与实战、简单的调用示例、文本补全API

651 阅读1分钟
pip install openai==0.28

示例1-List Models

image.png

import os
api_key = 'sk-xxx'
os.environ["OPENAI_API_KEY"] = api_key

serp_api = 'xxx'
os.environ["SERPAPI_API_KEY"] = serp_api

import openai
print(openai.Model.list())

image.png

示例2-Retrieve Model

print(openai.Model.retrieve("whisper-1"))

image.png

Completions API

文本补全API 给定一个Prompt,模型将返回一个或多个文本生成结果,并且还可以返回每个位置上备选tokens的概率。

from openai import OpenAI
client = OpenAI(api_key='sk-xxx')

completion = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},
    {"role": "user", "content": "请给我的花店起个名"}
  ]
)

print(completion.choices[0].message.content)