Dominic0406 commited on
Commit
3580374
1 Parent(s): bfc1826

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import gradio as gr
3
+ import time
4
+
5
+ # 设置OpenAI API密钥
6
+ openai.api_key = 'sk-proj-yhAZYjSv6CBPOuOKV0iYT3BlbkFJg5k1dOwWdh7WZxNstGIt'
7
+
8
+ # 初始化OpenAI客户端
9
+ client = openai.OpenAI(api_key=openai.api_key)
10
+
11
+ # 创建助手
12
+ assistant = client.beta.assistants.create(
13
+ name="医疗模型",
14
+ instructions="You are a personal math tutor. Write and run code to answer math questions.",
15
+ tools=[{"type": "code_interpreter"}],
16
+ model="gpt-4o",
17
+ )
18
+
19
+ # 定义与助手进行交互的函数
20
+ def chat_with_gpt4o(input_text):
21
+ # 创建对话线程和用户消息
22
+ thread = client.beta.threads.create()
23
+ message = client.beta.threads.messages.create(
24
+ thread_id=thread.id,
25
+ role="user",
26
+ content=input_text
27
+ )
28
+
29
+ # 开始运行助手
30
+ run = client.beta.threads.runs.create(
31
+ thread_id=thread.id,
32
+ assistant_id=assistant.id,
33
+ instructions="Please address the user as Jane Doe. The user has a premium account."
34
+ )
35
+
36
+ # 等待助手运行完成
37
+ while True:
38
+ run = client.beta.threads.runs.retrieve(run.id, thread_id=thread.id)
39
+ if run.status == 'completed':
40
+ break
41
+ time.sleep(1)
42
+
43
+ # 获取对话线程中的消息
44
+ messages = client.beta.threads.messages.list(thread_id=thread.id)
45
+
46
+ # 提取最后一条助手消息的内容
47
+ assistant_message = None
48
+ for msg in messages:
49
+ if msg.role == 'assistant':
50
+ assistant_message = msg.content[0].text.value
51
+
52
+ if assistant_message:
53
+ return assistant_message
54
+ else:
55
+ return "未找到助手的响应。"
56
+
57
+ # 创建Gradio接口
58
+ iface = gr.Interface(
59
+ fn=chat_with_gpt4o,
60
+ inputs="text",
61
+ outputs="text",
62
+ title="GPT-4o 医疗模型",
63
+ description="与GPT-4o进行对话并获取响应。"
64
+ )
65
+
66
+ # 启动接口
67
+ iface.launch()