admin管理员组

文章数量:1530518

在这篇博客中,我将介绍如何使用 OpenAI GPT-3 和 Python 来创建一个有趣且互动性强的对话界面。这个界面不仅可以处理连续的对话上下文,还能以彩色文本的形式展示用户和 AI 助手的对话,增强用户体验。

工具和技术

在开始之前,您需要确保已经安装了以下工具和库:

  • Python:一种广泛使用的高级编程语言。
  • OpenAI Python 库:用于与 OpenAI GPT-3 API 进行交互。
  • Termcolor:一个 Python 库,用于在终端中打印彩色文本。

实现步骤

以下是创建彩色对话界面的主要步骤:

1. 初始化 OpenAI 客户端

首先,我们需要配置 OpenAI 客户端,为此需要您的 API 密钥和 API 基础 URL。

from openai import OpenAI

client = OpenAI(
    api_key="您的API密钥",
    base_url="https://*************/v1"
)

2. 存储和管理对话历史

对话历史的管理对于维持对话上下文至关重要。我们使用一个列表来存储对话历史,并提供一个函数来清空这个列表。

conversation_history = []

def clear_conversation():
    global conversation_history
    conversation_history = []

 

3. 创建对话循环

我们创建一个循环来持续接收用户输入,并使用 OpenAI GPT-3 API 生成回复。此外,我们使用 termcolorcolored 函数为用户输入和助手回复添加颜色,使得对话更加直观。

from termcolor import colored
import sys

while True:
    user_input = input(colored("\n用户: ", "green"))
    # ... 处理用户输入和 API 调用 ...

 

4. 流式处理助手的回复

我们使用流式 API 来接收和展示助手的回复。这样,即使回复很长,用户也能实时看到每个部分的输出。

for chunk in response:
    if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content:
        print(colored(chunk.choices[0].delta.content, "blue"), end="")
        sys.stdout.flush()
        time.sleep(0.03)

5. 程序退出

用户可以通过输入特定的命令(如“退出”)来结束对话并退出程序。

for chunk in response:
    if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content:
        print(colored(chunk.choices[0].delta.content, "blue"), end="")
        sys.stdout.flush()
        time.sleep(0.03)

 

6.完整代码

from openai import OpenAI
from termcolor import colored
import sys
import time

# 初始化 OpenAI 客户端
client = OpenAI(
    api_key="****************************************",
    base_url="https://**************************/v1"
)

# 存储对话历史
conversation_history = []

# 清除对话历史的函数
def clear_conversation():
    global conversation_history
    conversation_history = []

# 主循环
while True:
    # 获取用户输入
    user_input = input(colored("\n用户: ", "green"))
    if user_input.lower() == "退出":
        break
    elif user_input.lower() == "清空对话":
        clear_conversation()
        print(colored("对话已清空。", "yellow"))
        continue

    # 更新对话历史
    conversation_history.append({"role": "user", "content": user_input})

    # 向 OpenAI 发送请求
    response = client.chatpletions.create(
        model="gpt-3.5-turbo-1106",
        messages=conversation_history,
        stream=True
    )

    # 输出助手的回复
    print(colored("助手: ", "blue"), end="")
    for chunk in response:
        if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content:
            print(colored(chunk.choices[0].delta.content, "blue"), end="")
            sys.stdout.flush()
            time.sleep(0.03) 

    # 更新对话历史
    conversation_history.append({"role": "assistant", "content": user_input})

# 程序退出
print(colored("\n程序已退出。", "red"))

7.代码运行截图

 

结语

这个简单的应用展示了如何利用 OpenAI GPT-3 和 Python 创建一个彩色的对话界面。通过这个界面,用户可以与 AI 助手进行自然且连续的对话,同时享受色彩带来的视觉体验。这只是展示 AI 对话界面潜力的一个小例子,未来的应用场景将更加广泛和丰富。

 

本文标签: 界面彩色openAIgpt