Spaces:
Sleeping
Sleeping
File size: 1,839 Bytes
3580374 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
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()
|