使用 OpenAI API 的 Python SDK,您可以轻松地完成对话完成的调用。以下是一个示例代码:

import openai
import os

openai.api_key = os.environ['OPENAI_API_KEY']

def generate_response(prompt):
    response = openai.Completion.create(
        engine='davinci',
        prompt=prompt,
        max_tokens=50,
        n=1,
        stop=None,
        temperature=0.5,
    )

    message = response.choices[0].text.strip()
    return message

prompt = 'Hello, how are you?'
response = generate_response(prompt)
print(response)

请确保您已经安装了 openai 包,并且将您的 OpenAI API 密钥存储在名为 OPENAI_API_KEY 的环境变量中。在这个示例中,我们使用了 davinci 引擎,设置了最大令牌数量为 50,生成了一个回复。

Python OpenAI API 对话完成示例代码

原文地址: https://www.cveoy.top/t/topic/lBtf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录