mbarnig commited on
Commit
9464595
·
verified ·
1 Parent(s): 4a2881e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -0
app.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import AsyncAssistantEventHandler
2
+ from openai import AsyncOpenAI
3
+ import gradio as gr
4
+ import asyncio
5
+
6
+ # Set your OpenAI API key here
7
+ client = AsyncOpenAI(
8
+ api_key="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"
9
+ )
10
+
11
+ assistantID = "asst_7xyER9PDcv13UJ22U2zz4x1z"
12
+
13
+ class EventHandler(AsyncAssistantEventHandler):
14
+ def __init__(self) -> None:
15
+ super().__init__()
16
+ self.response_text = ""
17
+
18
+ async def on_text_created(self, text) -> None:
19
+ self.response_text += str(text)
20
+
21
+ async def on_text_delta(self, delta, snapshot):
22
+ self.response_text += str(delta.value)
23
+
24
+ async def on_text_done(self, text):
25
+ pass
26
+
27
+ async def on_tool_call_created(self, tool_call):
28
+ self.response_text += f"\n[Tool Call]: {str(tool_call.type)}\n"
29
+
30
+ async def on_tool_call_delta(self, delta, snapshot):
31
+ if snapshot.id != getattr(self, "current_tool_call", None):
32
+ self.current_tool_call = snapshot.id
33
+ self.response_text += f"\n[Tool Call Delta]: {str(delta.type)}\n"
34
+
35
+ if delta.type == 'code_interpreter':
36
+ if delta.code_interpreter.input:
37
+ self.response_text += str(delta.code_interpreter.input)
38
+ if delta.code_interpreter.outputs:
39
+ self.response_text += "\n\n[Output]:\n"
40
+ for output in delta.code_interpreter.outputs:
41
+ if output.type == "logs":
42
+ self.response_text += f"\n{str(output.logs)}"
43
+
44
+ async def on_tool_call_done(self, text):
45
+ pass
46
+
47
+ # Initialize session variables
48
+ session_data = {"assistant_id": assistantID, "thread_id": None}
49
+
50
+ async def initialize_thread():
51
+ # Create a Thread
52
+ thread = await client.beta.threads.create()
53
+ # Store thread ID in session_data for later use
54
+ session_data["thread_id"] = thread.id
55
+
56
+ async def generate_response(user_input):
57
+ assistant_id = session_data["assistant_id"]
58
+ thread_id = session_data["thread_id"]
59
+
60
+ # Add a Message to the Thread
61
+ oai_message = await client.beta.threads.messages.create(
62
+ thread_id=thread_id,
63
+ role="user",
64
+ content=user_input
65
+ )
66
+
67
+ # Create and Stream a Run
68
+ event_handler = EventHandler()
69
+
70
+ async with client.beta.threads.runs.stream(
71
+ thread_id=thread_id,
72
+ assistant_id=assistant_id,
73
+ instructions="Please assist the user with their query.",
74
+ event_handler=event_handler,
75
+ ) as stream:
76
+ # Yield incremental updates
77
+ async for _ in stream:
78
+ await asyncio.sleep(0.1) # Small delay to mimic streaming
79
+ yield event_handler.response_text
80
+
81
+ # Gradio interface function (generator)
82
+ async def gradio_chat_interface(user_input):
83
+ # Create a new event loop if none exists (or if we are in a new thread)
84
+ try:
85
+ loop = asyncio.get_running_loop()
86
+ except RuntimeError:
87
+ loop = asyncio.new_event_loop()
88
+ asyncio.set_event_loop(loop)
89
+
90
+ # Initialize the thread if not already done
91
+ if session_data["thread_id"] is None:
92
+ await initialize_thread()
93
+
94
+ # Generate and yield responses
95
+ async for response in generate_response(user_input):
96
+ yield response
97
+
98
+ # Set up Gradio interface with streaming
99
+ interface = gr.Interface(
100
+ fn=gradio_chat_interface,
101
+ inputs="text",
102
+ outputs="text",
103
+ title="OpenAI Assistant with Gradio",
104
+ description="Ask anything and get an AI-generated response in real-time.",
105
+ live=False # Important to allow streaming-like behavior
106
+ )
107
+
108
+ # Launch the Gradio app
109
+ interface.launch()