Spaces:
Sleeping
Sleeping
import openai | |
import gradio as gr | |
import time | |
# 设置OpenAI API密钥 | |
openai.api_key = 'sk-proj-yhAZYjSv6CBPOuOKV0iYT3BlbkFJg5k1dOwWdh7WZxNstGIt' | |
# 初始化OpenAI客户端 | |
client = openai.OpenAI(api_key=openai.api_key) | |
# 创建助手 | |
assistant = client.beta.assistants.create( | |
name="医疗问诊", | |
instructions="You are a personal math tutor. Write and run code to answer math questions.", | |
tools=[{"type": "code_interpreter"}], | |
model="gpt-4o", | |
) | |
# 定义与助手进行交互的函数 | |
def chat_with_gpt4o(input_text): | |
# 创建对话线程和用户消息 | |
thread = client.beta.threads.create() | |
message = client.beta.threads.messages.create( | |
thread_id=thread.id, | |
role="user", | |
content=input_text | |
) | |
# 开始运行助手 | |
run = client.beta.threads.runs.create( | |
thread_id=thread.id, | |
assistant_id=assistant.id, | |
instructions="Please address the user as Jane Doe. The user has a premium account." | |
) | |
# 等待助手运行完成 | |
while True: | |
run = client.beta.threads.runs.retrieve(run.id, thread_id=thread.id) | |
if run.status == 'completed': | |
break | |
time.sleep(1) | |
# 获取对话线程中的消息 | |
messages = client.beta.threads.messages.list(thread_id=thread.id) | |
# 提取最后一条助手消息的内容 | |
assistant_message = None | |
for msg in messages: | |
if msg.role == 'assistant': | |
assistant_message = msg.content[0].text.value | |
if assistant_message: | |
return assistant_message | |
else: | |
return "未找到助手的响应。" | |
# 创建Gradio接口 | |
iface = gr.Interface( | |
fn=chat_with_gpt4o, | |
inputs="text", | |
outputs="text", | |
title="GPT-4o 医疗模型", | |
description="与GPT-4o进行对话并获取响应。" | |
) | |
# 启动接口 | |
iface.launch() | |