|
import os |
|
import openai |
|
import gradio as gr |
|
from gradio import ChatInterface |
|
from google.colab import userdata |
|
|
|
|
|
openai.api_key = os.environ['OPENAI_API_KEY'] |
|
|
|
def predict(inputs, chatbot): |
|
messages = [] |
|
|
|
|
|
for conv in chatbot: |
|
messages.append({"role": "user", "content": conv[0]}) |
|
messages.append({"role": "assistant", "content": conv[1]}) |
|
|
|
|
|
messages.append({"role": "user", "content": inputs}) |
|
|
|
try: |
|
|
|
response = openai.ChatCompletion.create( |
|
model='gpt-4', |
|
messages=messages, |
|
temperature=1.0, |
|
stream=True |
|
) |
|
|
|
partial_message = "" |
|
for chunk in response: |
|
if 'choices' in chunk and len(chunk['choices']) > 0: |
|
if 'delta' in chunk['choices'][0] and 'content' in chunk['choices'][0]['delta']: |
|
content = chunk['choices'][0]['delta']['content'] |
|
partial_message += content |
|
yield partial_message |
|
|
|
except Exception as e: |
|
yield f"發生錯誤: {str(e)}" |
|
|
|
|
|
chat_interface = gr.ChatInterface( |
|
predict, |
|
chatbot=gr.Chatbot(height=600), |
|
title="AI 聊天助手", |
|
description="請輸入您的問題", |
|
) |
|
|
|
if __name__ == "__main__": |
|
chat_interface.launch() |