jdmorzan commited on
Commit
e6d4920
verified
1 Parent(s): 68923c2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -122
app.py CHANGED
@@ -1,7 +1,7 @@
1
  # app.py
2
  import asyncio
3
  import gradio as gr
4
- from typing import List, Tuple, AsyncGenerator
5
  from agents import FileSearchTool, Agent, ModelSettings, TResponseInputItem, Runner, RunConfig, trace
6
  import os
7
  from dotenv import load_dotenv
@@ -28,8 +28,7 @@ my_agent = Agent(
28
  temperature=1,
29
  top_p=1,
30
  max_tokens=2048,
31
- store=True,
32
- stream=True # Enable streaming in model settings
33
  )
34
  )
35
 
@@ -49,71 +48,29 @@ def _to_items_from_history(history: List[Tuple[str, str]]) -> List[TResponseInpu
49
  })
50
  return items
51
 
52
- async def agent_reply_stream(message: str, history: List[Tuple[str, str]]) -> AsyncGenerator[str, None]:
53
- """Streaming handler for Gradio ChatInterface."""
54
  conversation_items = _to_items_from_history(history)
55
  conversation_items.append({
56
  "role": "user",
57
  "content": [{"type": "input_text", "text": message}],
58
  })
59
 
60
- accumulated_response = ""
61
-
62
  with trace("Gradio message"):
63
- # Use streaming version of Runner.run
64
- async for chunk in Runner.run_stream(
65
  my_agent,
66
  input=conversation_items,
67
- run_config=RunConfig(
68
- trace_metadata={
69
- "__trace_source__": "agent-builder",
70
- "workflow_id": WORKFLOW_ID
71
- },
72
- stream=True
73
- )
74
- ):
75
- # Extract text from the chunk
76
- # The exact format depends on your agents library implementation
77
- if hasattr(chunk, 'delta'):
78
- chunk_text = chunk.delta
79
- elif hasattr(chunk, 'text'):
80
- chunk_text = chunk.text
81
- elif isinstance(chunk, str):
82
- chunk_text = chunk
83
- else:
84
- # Adapt this based on your actual chunk structure
85
- chunk_text = str(chunk)
86
-
87
- accumulated_response += chunk_text
88
- yield accumulated_response
89
-
90
- # Synchronous wrapper for Gradio (if needed)
91
- def agent_reply_stream_sync(message: str, history: List[Tuple[str, str]]):
92
- """Synchronous wrapper for the async streaming function."""
93
- async def run():
94
- accumulated = ""
95
- async for chunk in agent_reply_stream(message, history):
96
- accumulated = chunk
97
- yield accumulated
98
-
99
- # Run the async generator in a sync context
100
- loop = asyncio.new_event_loop()
101
- asyncio.set_event_loop(loop)
102
 
103
- try:
104
- gen = run()
105
- while True:
106
- try:
107
- future = asyncio.run_coroutine_threadsafe(gen.__anext__(), loop)
108
- yield future.result()
109
- except StopAsyncIteration:
110
- break
111
- finally:
112
- loop.close()
113
 
114
- # --- Gradio ChatInterface with Streaming ---
115
  demo = gr.ChatInterface(
116
- fn=agent_reply_stream_sync, # Use the streaming function
117
  title="My agent (FileSearch-powered)",
118
  description=(
119
  "Este chat usa un agente con FileSearchTool. "
@@ -122,72 +79,9 @@ demo = gr.ChatInterface(
122
  examples=["驴Qu茅 informaci贸n hay sobre el proyecto X?", "Resume el documento m谩s reciente."],
123
  theme="soft",
124
  submit_btn="Enviar"
 
125
  )
126
 
127
- # Alternative: Using gr.Blocks for more control
128
- def create_blocks_interface():
129
- with gr.Blocks(theme="soft") as demo:
130
- gr.Markdown("# My agent (FileSearch-powered)")
131
- gr.Markdown(
132
- "Este chat usa un agente con FileSearchTool. "
133
- "Escribe tu pregunta y el agente buscar谩 primero en el file search antes de responder."
134
- )
135
-
136
- chatbot = gr.Chatbot()
137
- msg = gr.Textbox(
138
- label="Mensaje",
139
- placeholder="Escribe tu pregunta aqu铆...",
140
- lines=2
141
- )
142
-
143
- with gr.Row():
144
- submit = gr.Button("Enviar", variant="primary")
145
- clear = gr.Button("Limpiar")
146
-
147
- async def respond(message, chat_history):
148
- # Add user message to chat history
149
- chat_history.append((message, ""))
150
-
151
- # Stream the response
152
- async for partial_response in agent_reply_stream(message, chat_history[:-1]):
153
- chat_history[-1] = (message, partial_response)
154
- yield "", chat_history
155
-
156
- submit.click(
157
- respond,
158
- inputs=[msg, chatbot],
159
- outputs=[msg, chatbot],
160
- queue=True
161
- )
162
-
163
- msg.submit(
164
- respond,
165
- inputs=[msg, chatbot],
166
- outputs=[msg, chatbot],
167
- queue=True
168
- )
169
-
170
- clear.click(
171
- lambda: ([], ""),
172
- outputs=[chatbot, msg]
173
- )
174
-
175
- # Example buttons
176
- gr.Examples(
177
- examples=[
178
- "驴Qu茅 informaci贸n hay sobre el proyecto X?",
179
- "Resume el documento m谩s reciente."
180
- ],
181
- inputs=msg
182
- )
183
-
184
- return demo
185
-
186
- # --- Launch the app ---
187
  if __name__ == "__main__":
188
- # Option 1: Use ChatInterface (simpler but less control)
189
- demo.launch(queue=True) # Enable queue for streaming
190
-
191
- # Option 2: Use Blocks interface (more control)
192
- # blocks_demo = create_blocks_interface()
193
- # blocks_demo.launch(queue=True)
 
1
  # app.py
2
  import asyncio
3
  import gradio as gr
4
+ from typing import List, Tuple
5
  from agents import FileSearchTool, Agent, ModelSettings, TResponseInputItem, Runner, RunConfig, trace
6
  import os
7
  from dotenv import load_dotenv
 
28
  temperature=1,
29
  top_p=1,
30
  max_tokens=2048,
31
+ store=True
 
32
  )
33
  )
34
 
 
48
  })
49
  return items
50
 
51
+ async def agent_reply(message: str, history: List[Tuple[str, str]]):
52
+ """Handler for Gradio ChatInterface."""
53
  conversation_items = _to_items_from_history(history)
54
  conversation_items.append({
55
  "role": "user",
56
  "content": [{"type": "input_text", "text": message}],
57
  })
58
 
 
 
59
  with trace("Gradio message"):
60
+ result = await Runner.run(
 
61
  my_agent,
62
  input=conversation_items,
63
+ run_config=RunConfig(trace_metadata={
64
+ "__trace_source__": "agent-builder",
65
+ "workflow_id": WORKFLOW_ID
66
+ })
67
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
+ return result.final_output_as(str)
 
 
 
 
 
 
 
 
 
70
 
71
+ # --- Updated Gradio ChatInterface ---
72
  demo = gr.ChatInterface(
73
+ fn=agent_reply,
74
  title="My agent (FileSearch-powered)",
75
  description=(
76
  "Este chat usa un agente con FileSearchTool. "
 
79
  examples=["驴Qu茅 informaci贸n hay sobre el proyecto X?", "Resume el documento m谩s reciente."],
80
  theme="soft",
81
  submit_btn="Enviar"
82
+ # Removed clear_btn as it's not a valid parameter
83
  )
84
 
85
+ # If you need to run the app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  if __name__ == "__main__":
87
+ demo.launch()