2024年1月15日更新:Key已无效,请自行设置key。

这里分享一个python代码,提前安装好gradio包(pip install gradio),即可直接运行实现和GPT模型的对话。初学者可以尝试体验一下,并根据自己的兴趣修改代码。

import gradio as gr
import requests

# 设置您的OpenAI API凭据
api_key = '这里输入你的openai key'

# 初始化对话历史
history = []

# 定义对话函数
def chat_with_gpt(prompt):
    global history

    # 将用户的消息添加到历史中
    history.append({'role': 'user', 'content': prompt})

    response = requests.post(
        'https://api.openai.com/v1/chat/completions',
        headers={'Authorization': f'Bearer {api_key}'},
        json={
            'model': 'gpt-3.5-turbo-16k',
            'messages': history,
            'max_tokens': 2000,
            'temperature': 0.5
        }
    )
    response.raise_for_status()

    # 将模型的回复添加到历史中
    model_message = response.json()['choices'][0]['message']['content']
    history.append({'role': 'assistant', 'content': model_message})

    # 将历史消息转化为文本格式,以便在界面中显示
    history_text = "\n".join([f"{message['role']}: {message['content']}" for message in history])
    return history_text

# 定义 Gradio 接口函数
def chat_bot(输入):
    response = chat_with_gpt(输入)
    return response

# 创建 Gradio 接口
iface = gr.Interface(fn=chat_bot, inputs="text", outputs="text", title="GPT-3.5-Turbo-16K")

# 启动 Gradio 接口
iface.launch(share=True)