agno 2.3.8__py3-none-any.whl → 2.3.10__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. agno/agent/agent.py +134 -94
  2. agno/db/mysql/__init__.py +2 -1
  3. agno/db/mysql/async_mysql.py +2888 -0
  4. agno/db/mysql/mysql.py +17 -8
  5. agno/db/mysql/utils.py +139 -6
  6. agno/db/postgres/async_postgres.py +10 -5
  7. agno/db/postgres/postgres.py +7 -2
  8. agno/db/schemas/evals.py +1 -0
  9. agno/db/singlestore/singlestore.py +5 -1
  10. agno/db/sqlite/async_sqlite.py +3 -3
  11. agno/eval/__init__.py +10 -0
  12. agno/eval/accuracy.py +11 -8
  13. agno/eval/agent_as_judge.py +861 -0
  14. agno/eval/base.py +29 -0
  15. agno/eval/utils.py +2 -1
  16. agno/exceptions.py +7 -0
  17. agno/knowledge/embedder/openai.py +8 -8
  18. agno/knowledge/knowledge.py +1142 -176
  19. agno/media.py +22 -6
  20. agno/models/aws/claude.py +8 -7
  21. agno/models/base.py +61 -2
  22. agno/models/deepseek/deepseek.py +67 -0
  23. agno/models/google/gemini.py +134 -51
  24. agno/models/google/utils.py +22 -0
  25. agno/models/message.py +5 -0
  26. agno/models/openai/chat.py +4 -0
  27. agno/os/app.py +64 -74
  28. agno/os/interfaces/a2a/router.py +3 -4
  29. agno/os/interfaces/agui/router.py +2 -0
  30. agno/os/router.py +3 -1607
  31. agno/os/routers/agents/__init__.py +3 -0
  32. agno/os/routers/agents/router.py +581 -0
  33. agno/os/routers/agents/schema.py +261 -0
  34. agno/os/routers/evals/evals.py +26 -6
  35. agno/os/routers/evals/schemas.py +34 -2
  36. agno/os/routers/evals/utils.py +77 -18
  37. agno/os/routers/knowledge/knowledge.py +1 -1
  38. agno/os/routers/teams/__init__.py +3 -0
  39. agno/os/routers/teams/router.py +496 -0
  40. agno/os/routers/teams/schema.py +257 -0
  41. agno/os/routers/workflows/__init__.py +3 -0
  42. agno/os/routers/workflows/router.py +545 -0
  43. agno/os/routers/workflows/schema.py +75 -0
  44. agno/os/schema.py +1 -559
  45. agno/os/utils.py +139 -2
  46. agno/team/team.py +87 -24
  47. agno/tools/file_generation.py +12 -6
  48. agno/tools/firecrawl.py +15 -7
  49. agno/tools/function.py +37 -23
  50. agno/tools/shopify.py +1519 -0
  51. agno/tools/spotify.py +2 -5
  52. agno/utils/hooks.py +64 -5
  53. agno/utils/http.py +2 -2
  54. agno/utils/media.py +11 -1
  55. agno/utils/print_response/agent.py +8 -0
  56. agno/utils/print_response/team.py +8 -0
  57. agno/vectordb/pgvector/pgvector.py +88 -51
  58. agno/workflow/parallel.py +5 -3
  59. agno/workflow/step.py +14 -2
  60. agno/workflow/types.py +38 -2
  61. agno/workflow/workflow.py +12 -4
  62. {agno-2.3.8.dist-info → agno-2.3.10.dist-info}/METADATA +7 -2
  63. {agno-2.3.8.dist-info → agno-2.3.10.dist-info}/RECORD +66 -52
  64. {agno-2.3.8.dist-info → agno-2.3.10.dist-info}/WHEEL +0 -0
  65. {agno-2.3.8.dist-info → agno-2.3.10.dist-info}/licenses/LICENSE +0 -0
  66. {agno-2.3.8.dist-info → agno-2.3.10.dist-info}/top_level.txt +0 -0
agno/os/router.py CHANGED
@@ -1,31 +1,18 @@
1
- import json
2
- from typing import TYPE_CHECKING, Any, AsyncGenerator, Callable, Dict, List, Optional, Union, cast
3
- from uuid import uuid4
1
+ from typing import TYPE_CHECKING, List, Optional, Union, cast
4
2
 
5
3
  from fastapi import (
6
4
  APIRouter,
7
- BackgroundTasks,
8
5
  Depends,
9
- File,
10
- Form,
11
6
  HTTPException,
12
- Request,
13
- UploadFile,
14
- WebSocket,
15
7
  )
16
- from fastapi.responses import JSONResponse, StreamingResponse
8
+ from fastapi.responses import JSONResponse
17
9
  from packaging import version
18
- from pydantic import BaseModel
19
10
 
20
11
  from agno.agent.agent import Agent
21
12
  from agno.db.base import AsyncBaseDb
22
13
  from agno.db.migrations.manager import MigrationManager
23
- from agno.exceptions import InputCheckError, OutputCheckError
24
- from agno.media import Audio, Image, Video
25
- from agno.media import File as FileMedia
26
- from agno.os.auth import get_authentication_dependency, validate_websocket_token
14
+ from agno.os.auth import get_authentication_dependency
27
15
  from agno.os.schema import (
28
- AgentResponse,
29
16
  AgentSummaryResponse,
30
17
  BadRequestResponse,
31
18
  ConfigResponse,
@@ -33,593 +20,21 @@ from agno.os.schema import (
33
20
  InternalServerErrorResponse,
34
21
  Model,
35
22
  NotFoundResponse,
36
- TeamResponse,
37
23
  TeamSummaryResponse,
38
24
  UnauthenticatedResponse,
39
25
  ValidationErrorResponse,
40
- WorkflowResponse,
41
26
  WorkflowSummaryResponse,
42
27
  )
43
28
  from agno.os.settings import AgnoAPISettings
44
29
  from agno.os.utils import (
45
- get_agent_by_id,
46
30
  get_db,
47
- get_team_by_id,
48
- get_workflow_by_id,
49
- process_audio,
50
- process_document,
51
- process_image,
52
- process_video,
53
31
  )
54
- from agno.run.agent import RunErrorEvent, RunOutput, RunOutputEvent
55
- from agno.run.team import RunErrorEvent as TeamRunErrorEvent
56
- from agno.run.team import TeamRunOutputEvent
57
- from agno.run.workflow import WorkflowErrorEvent, WorkflowRunOutput, WorkflowRunOutputEvent
58
32
  from agno.team.team import Team
59
- from agno.utils.log import log_debug, log_error, log_warning, logger
60
- from agno.workflow.workflow import Workflow
61
33
 
62
34
  if TYPE_CHECKING:
63
35
  from agno.os.app import AgentOS
64
36
 
65
37
 
66
- async def _get_request_kwargs(request: Request, endpoint_func: Callable) -> Dict[str, Any]:
67
- """Given a Request and an endpoint function, return a dictionary with all extra form data fields.
68
- Args:
69
- request: The FastAPI Request object
70
- endpoint_func: The function exposing the endpoint that received the request
71
-
72
- Returns:
73
- A dictionary of kwargs
74
- """
75
- import inspect
76
-
77
- form_data = await request.form()
78
- sig = inspect.signature(endpoint_func)
79
- known_fields = set(sig.parameters.keys())
80
- kwargs: Dict[str, Any] = {key: value for key, value in form_data.items() if key not in known_fields}
81
-
82
- # Handle JSON parameters. They are passed as strings and need to be deserialized.
83
- if session_state := kwargs.get("session_state"):
84
- try:
85
- if isinstance(session_state, str):
86
- session_state_dict = json.loads(session_state) # type: ignore
87
- kwargs["session_state"] = session_state_dict
88
- except json.JSONDecodeError:
89
- kwargs.pop("session_state")
90
- log_warning(f"Invalid session_state parameter couldn't be loaded: {session_state}")
91
-
92
- if dependencies := kwargs.get("dependencies"):
93
- try:
94
- if isinstance(dependencies, str):
95
- dependencies_dict = json.loads(dependencies) # type: ignore
96
- kwargs["dependencies"] = dependencies_dict
97
- except json.JSONDecodeError:
98
- kwargs.pop("dependencies")
99
- log_warning(f"Invalid dependencies parameter couldn't be loaded: {dependencies}")
100
-
101
- if metadata := kwargs.get("metadata"):
102
- try:
103
- if isinstance(metadata, str):
104
- metadata_dict = json.loads(metadata) # type: ignore
105
- kwargs["metadata"] = metadata_dict
106
- except json.JSONDecodeError:
107
- kwargs.pop("metadata")
108
- log_warning(f"Invalid metadata parameter couldn't be loaded: {metadata}")
109
-
110
- if knowledge_filters := kwargs.get("knowledge_filters"):
111
- try:
112
- if isinstance(knowledge_filters, str):
113
- knowledge_filters_dict = json.loads(knowledge_filters) # type: ignore
114
-
115
- # Try to deserialize FilterExpr objects
116
- from agno.filters import from_dict
117
-
118
- # Check if it's a single FilterExpr dict or a list of FilterExpr dicts
119
- if isinstance(knowledge_filters_dict, dict) and "op" in knowledge_filters_dict:
120
- # Single FilterExpr - convert to list format
121
- kwargs["knowledge_filters"] = [from_dict(knowledge_filters_dict)]
122
- elif isinstance(knowledge_filters_dict, list):
123
- # List of FilterExprs or mixed content
124
- deserialized = []
125
- for item in knowledge_filters_dict:
126
- if isinstance(item, dict) and "op" in item:
127
- deserialized.append(from_dict(item))
128
- else:
129
- # Keep non-FilterExpr items as-is
130
- deserialized.append(item)
131
- kwargs["knowledge_filters"] = deserialized
132
- else:
133
- # Regular dict filter
134
- kwargs["knowledge_filters"] = knowledge_filters_dict
135
- except json.JSONDecodeError:
136
- kwargs.pop("knowledge_filters")
137
- log_warning(f"Invalid knowledge_filters parameter couldn't be loaded: {knowledge_filters}")
138
- except ValueError as e:
139
- # Filter deserialization failed
140
- kwargs.pop("knowledge_filters")
141
- log_warning(f"Invalid FilterExpr in knowledge_filters: {e}")
142
-
143
- # Handle output_schema - convert JSON schema to dynamic Pydantic model
144
- if output_schema := kwargs.get("output_schema"):
145
- try:
146
- if isinstance(output_schema, str):
147
- from agno.os.utils import json_schema_to_pydantic_model
148
-
149
- schema_dict = json.loads(output_schema)
150
- dynamic_model = json_schema_to_pydantic_model(schema_dict)
151
- kwargs["output_schema"] = dynamic_model
152
- except json.JSONDecodeError:
153
- kwargs.pop("output_schema")
154
- log_warning(f"Invalid output_schema JSON: {output_schema}")
155
- except Exception as e:
156
- kwargs.pop("output_schema")
157
- log_warning(f"Failed to create output_schema model: {e}")
158
-
159
- # Parse boolean and null values
160
- for key, value in kwargs.items():
161
- if isinstance(value, str) and value.lower() in ["true", "false"]:
162
- kwargs[key] = value.lower() == "true"
163
- elif isinstance(value, str) and value.lower() in ["null", "none"]:
164
- kwargs[key] = None
165
-
166
- return kwargs
167
-
168
-
169
- def format_sse_event(event: Union[RunOutputEvent, TeamRunOutputEvent, WorkflowRunOutputEvent]) -> str:
170
- """Parse JSON data into SSE-compliant format.
171
-
172
- Args:
173
- event_dict: Dictionary containing the event data
174
-
175
- Returns:
176
- SSE-formatted response:
177
-
178
- ```
179
- event: EventName
180
- data: { ... }
181
-
182
- event: AnotherEventName
183
- data: { ... }
184
- ```
185
- """
186
- try:
187
- # Parse the JSON to extract the event type
188
- event_type = event.event or "message"
189
-
190
- # Serialize to valid JSON with double quotes and no newlines
191
- clean_json = event.to_json(separators=(",", ":"), indent=None)
192
-
193
- return f"event: {event_type}\ndata: {clean_json}\n\n"
194
- except json.JSONDecodeError:
195
- clean_json = event.to_json(separators=(",", ":"), indent=None)
196
- return f"event: message\ndata: {clean_json}\n\n"
197
-
198
-
199
- class WebSocketManager:
200
- """Manages WebSocket connections for workflow runs"""
201
-
202
- active_connections: Dict[str, WebSocket] # {run_id: websocket}
203
- authenticated_connections: Dict[WebSocket, bool] # {websocket: is_authenticated}
204
-
205
- def __init__(
206
- self,
207
- active_connections: Optional[Dict[str, WebSocket]] = None,
208
- ):
209
- # Store active connections: {run_id: websocket}
210
- self.active_connections = active_connections or {}
211
- # Track authentication state for each websocket
212
- self.authenticated_connections = {}
213
-
214
- async def connect(self, websocket: WebSocket, requires_auth: bool = True):
215
- """Accept WebSocket connection"""
216
- await websocket.accept()
217
- logger.debug("WebSocket connected")
218
-
219
- # If auth is not required, mark as authenticated immediately
220
- self.authenticated_connections[websocket] = not requires_auth
221
-
222
- # Send connection confirmation with auth requirement info
223
- await websocket.send_text(
224
- json.dumps(
225
- {
226
- "event": "connected",
227
- "message": (
228
- "Connected to workflow events. Please authenticate to continue."
229
- if requires_auth
230
- else "Connected to workflow events. Authentication not required."
231
- ),
232
- "requires_auth": requires_auth,
233
- }
234
- )
235
- )
236
-
237
- async def authenticate_websocket(self, websocket: WebSocket):
238
- """Mark a WebSocket connection as authenticated"""
239
- self.authenticated_connections[websocket] = True
240
- logger.debug("WebSocket authenticated")
241
-
242
- # Send authentication confirmation
243
- await websocket.send_text(
244
- json.dumps(
245
- {
246
- "event": "authenticated",
247
- "message": "Authentication successful. You can now send commands.",
248
- }
249
- )
250
- )
251
-
252
- def is_authenticated(self, websocket: WebSocket) -> bool:
253
- """Check if a WebSocket connection is authenticated"""
254
- return self.authenticated_connections.get(websocket, False)
255
-
256
- async def register_workflow_websocket(self, run_id: str, websocket: WebSocket):
257
- """Register a workflow run with its WebSocket connection"""
258
- self.active_connections[run_id] = websocket
259
- logger.debug(f"Registered WebSocket for run_id: {run_id}")
260
-
261
- async def disconnect_by_run_id(self, run_id: str):
262
- """Remove WebSocket connection by run_id"""
263
- if run_id in self.active_connections:
264
- websocket = self.active_connections[run_id]
265
- del self.active_connections[run_id]
266
- # Clean up authentication state
267
- if websocket in self.authenticated_connections:
268
- del self.authenticated_connections[websocket]
269
- logger.debug(f"WebSocket disconnected for run_id: {run_id}")
270
-
271
- async def disconnect_websocket(self, websocket: WebSocket):
272
- """Remove WebSocket connection and clean up all associated state"""
273
- # Remove from authenticated connections
274
- if websocket in self.authenticated_connections:
275
- del self.authenticated_connections[websocket]
276
-
277
- # Remove from active connections
278
- runs_to_remove = [run_id for run_id, ws in self.active_connections.items() if ws == websocket]
279
- for run_id in runs_to_remove:
280
- del self.active_connections[run_id]
281
-
282
- logger.debug("WebSocket disconnected and cleaned up")
283
-
284
- async def get_websocket_for_run(self, run_id: str) -> Optional[WebSocket]:
285
- """Get WebSocket connection for a workflow run"""
286
- return self.active_connections.get(run_id)
287
-
288
-
289
- # Global manager instance
290
- websocket_manager = WebSocketManager(
291
- active_connections={},
292
- )
293
-
294
-
295
- async def agent_response_streamer(
296
- agent: Agent,
297
- message: str,
298
- session_id: Optional[str] = None,
299
- user_id: Optional[str] = None,
300
- images: Optional[List[Image]] = None,
301
- audio: Optional[List[Audio]] = None,
302
- videos: Optional[List[Video]] = None,
303
- files: Optional[List[FileMedia]] = None,
304
- background_tasks: Optional[BackgroundTasks] = None,
305
- **kwargs: Any,
306
- ) -> AsyncGenerator:
307
- try:
308
- # Pass background_tasks if provided
309
- if background_tasks is not None:
310
- kwargs["background_tasks"] = background_tasks
311
-
312
- run_response = agent.arun(
313
- input=message,
314
- session_id=session_id,
315
- user_id=user_id,
316
- images=images,
317
- audio=audio,
318
- videos=videos,
319
- files=files,
320
- stream=True,
321
- stream_events=True,
322
- **kwargs,
323
- )
324
- async for run_response_chunk in run_response:
325
- yield format_sse_event(run_response_chunk) # type: ignore
326
- except (InputCheckError, OutputCheckError) as e:
327
- error_response = RunErrorEvent(
328
- content=str(e),
329
- error_type=e.type,
330
- error_id=e.error_id,
331
- additional_data=e.additional_data,
332
- )
333
- yield format_sse_event(error_response)
334
- except Exception as e:
335
- import traceback
336
-
337
- traceback.print_exc(limit=3)
338
- error_response = RunErrorEvent(
339
- content=str(e),
340
- )
341
- yield format_sse_event(error_response)
342
-
343
-
344
- async def agent_continue_response_streamer(
345
- agent: Agent,
346
- run_id: Optional[str] = None,
347
- updated_tools: Optional[List] = None,
348
- session_id: Optional[str] = None,
349
- user_id: Optional[str] = None,
350
- background_tasks: Optional[BackgroundTasks] = None,
351
- ) -> AsyncGenerator:
352
- try:
353
- continue_response = agent.acontinue_run(
354
- run_id=run_id,
355
- updated_tools=updated_tools,
356
- session_id=session_id,
357
- user_id=user_id,
358
- stream=True,
359
- stream_events=True,
360
- background_tasks=background_tasks,
361
- )
362
- async for run_response_chunk in continue_response:
363
- yield format_sse_event(run_response_chunk) # type: ignore
364
- except (InputCheckError, OutputCheckError) as e:
365
- error_response = RunErrorEvent(
366
- content=str(e),
367
- error_type=e.type,
368
- error_id=e.error_id,
369
- additional_data=e.additional_data,
370
- )
371
- yield format_sse_event(error_response)
372
-
373
- except Exception as e:
374
- import traceback
375
-
376
- traceback.print_exc(limit=3)
377
- error_response = RunErrorEvent(
378
- content=str(e),
379
- error_type=e.type if hasattr(e, "type") else None,
380
- error_id=e.error_id if hasattr(e, "error_id") else None,
381
- )
382
- yield format_sse_event(error_response)
383
- return
384
-
385
-
386
- async def team_response_streamer(
387
- team: Team,
388
- message: str,
389
- session_id: Optional[str] = None,
390
- user_id: Optional[str] = None,
391
- images: Optional[List[Image]] = None,
392
- audio: Optional[List[Audio]] = None,
393
- videos: Optional[List[Video]] = None,
394
- files: Optional[List[FileMedia]] = None,
395
- background_tasks: Optional[BackgroundTasks] = None,
396
- **kwargs: Any,
397
- ) -> AsyncGenerator:
398
- """Run the given team asynchronously and yield its response"""
399
- try:
400
- # Pass background_tasks if provided
401
- if background_tasks is not None:
402
- kwargs["background_tasks"] = background_tasks
403
-
404
- run_response = team.arun(
405
- input=message,
406
- session_id=session_id,
407
- user_id=user_id,
408
- images=images,
409
- audio=audio,
410
- videos=videos,
411
- files=files,
412
- stream=True,
413
- stream_events=True,
414
- **kwargs,
415
- )
416
- async for run_response_chunk in run_response:
417
- yield format_sse_event(run_response_chunk) # type: ignore
418
- except (InputCheckError, OutputCheckError) as e:
419
- error_response = TeamRunErrorEvent(
420
- content=str(e),
421
- error_type=e.type,
422
- error_id=e.error_id,
423
- additional_data=e.additional_data,
424
- )
425
- yield format_sse_event(error_response)
426
-
427
- except Exception as e:
428
- import traceback
429
-
430
- traceback.print_exc()
431
- error_response = TeamRunErrorEvent(
432
- content=str(e),
433
- error_type=e.type if hasattr(e, "type") else None,
434
- error_id=e.error_id if hasattr(e, "error_id") else None,
435
- )
436
- yield format_sse_event(error_response)
437
- return
438
-
439
-
440
- async def handle_workflow_via_websocket(websocket: WebSocket, message: dict, os: "AgentOS"):
441
- """Handle workflow execution directly via WebSocket"""
442
- try:
443
- workflow_id = message.get("workflow_id")
444
- session_id = message.get("session_id")
445
- user_message = message.get("message", "")
446
- user_id = message.get("user_id")
447
-
448
- if not workflow_id:
449
- await websocket.send_text(json.dumps({"event": "error", "error": "workflow_id is required"}))
450
- return
451
-
452
- # Get workflow from OS
453
- workflow = get_workflow_by_id(workflow_id, os.workflows)
454
- if not workflow:
455
- await websocket.send_text(json.dumps({"event": "error", "error": f"Workflow {workflow_id} not found"}))
456
- return
457
-
458
- # Generate session_id if not provided
459
- # Use workflow's default session_id if not provided in message
460
- if not session_id:
461
- if workflow.session_id:
462
- session_id = workflow.session_id
463
- else:
464
- session_id = str(uuid4())
465
-
466
- # Execute workflow in background with streaming
467
- workflow_result = await workflow.arun( # type: ignore
468
- input=user_message,
469
- session_id=session_id,
470
- user_id=user_id,
471
- stream=True,
472
- stream_events=True,
473
- background=True,
474
- websocket=websocket,
475
- )
476
-
477
- workflow_run_output = cast(WorkflowRunOutput, workflow_result)
478
-
479
- await websocket_manager.register_workflow_websocket(workflow_run_output.run_id, websocket) # type: ignore
480
-
481
- except (InputCheckError, OutputCheckError) as e:
482
- await websocket.send_text(
483
- json.dumps(
484
- {
485
- "event": "error",
486
- "error": str(e),
487
- "error_type": e.type,
488
- "error_id": e.error_id,
489
- "additional_data": e.additional_data,
490
- }
491
- )
492
- )
493
- except Exception as e:
494
- logger.error(f"Error executing workflow via WebSocket: {e}")
495
- error_payload = {
496
- "event": "error",
497
- "error": str(e),
498
- "error_type": e.type if hasattr(e, "type") else None,
499
- "error_id": e.error_id if hasattr(e, "error_id") else None,
500
- }
501
- error_payload = {k: v for k, v in error_payload.items() if v is not None}
502
- await websocket.send_text(json.dumps(error_payload))
503
-
504
-
505
- async def workflow_response_streamer(
506
- workflow: Workflow,
507
- input: Optional[Union[str, Dict[str, Any], List[Any], BaseModel]] = None,
508
- session_id: Optional[str] = None,
509
- user_id: Optional[str] = None,
510
- background_tasks: Optional[BackgroundTasks] = None,
511
- **kwargs: Any,
512
- ) -> AsyncGenerator:
513
- try:
514
- # Pass background_tasks if provided
515
- if background_tasks is not None:
516
- kwargs["background_tasks"] = background_tasks
517
-
518
- run_response = workflow.arun(
519
- input=input,
520
- session_id=session_id,
521
- user_id=user_id,
522
- stream=True,
523
- stream_events=True,
524
- **kwargs,
525
- )
526
-
527
- async for run_response_chunk in run_response:
528
- yield format_sse_event(run_response_chunk) # type: ignore
529
-
530
- except (InputCheckError, OutputCheckError) as e:
531
- error_response = WorkflowErrorEvent(
532
- error=str(e),
533
- error_type=e.type,
534
- error_id=e.error_id,
535
- additional_data=e.additional_data,
536
- )
537
- yield format_sse_event(error_response)
538
-
539
- except Exception as e:
540
- import traceback
541
-
542
- traceback.print_exc()
543
- error_response = WorkflowErrorEvent(
544
- error=str(e),
545
- error_type=e.type if hasattr(e, "type") else None,
546
- error_id=e.error_id if hasattr(e, "error_id") else None,
547
- )
548
- yield format_sse_event(error_response)
549
- return
550
-
551
-
552
- def get_websocket_router(
553
- os: "AgentOS",
554
- settings: AgnoAPISettings = AgnoAPISettings(),
555
- ) -> APIRouter:
556
- """
557
- Create WebSocket router without HTTP authentication dependencies.
558
- WebSocket endpoints handle authentication internally via message-based auth.
559
- """
560
- ws_router = APIRouter()
561
-
562
- @ws_router.websocket(
563
- "/workflows/ws",
564
- name="workflow_websocket",
565
- )
566
- async def workflow_websocket_endpoint(websocket: WebSocket):
567
- """WebSocket endpoint for receiving real-time workflow events"""
568
- requires_auth = bool(settings.os_security_key)
569
- await websocket_manager.connect(websocket, requires_auth=requires_auth)
570
-
571
- try:
572
- while True:
573
- data = await websocket.receive_text()
574
- message = json.loads(data)
575
- action = message.get("action")
576
-
577
- # Handle authentication first
578
- if action == "authenticate":
579
- token = message.get("token")
580
- if not token:
581
- await websocket.send_text(json.dumps({"event": "auth_error", "error": "Token is required"}))
582
- continue
583
-
584
- if validate_websocket_token(token, settings):
585
- await websocket_manager.authenticate_websocket(websocket)
586
- else:
587
- await websocket.send_text(json.dumps({"event": "auth_error", "error": "Invalid token"}))
588
- continue
589
-
590
- # Check authentication for all other actions (only when required)
591
- elif requires_auth and not websocket_manager.is_authenticated(websocket):
592
- await websocket.send_text(
593
- json.dumps(
594
- {
595
- "event": "auth_required",
596
- "error": "Authentication required. Send authenticate action with valid token.",
597
- }
598
- )
599
- )
600
- continue
601
-
602
- # Handle authenticated actions
603
- elif action == "ping":
604
- await websocket.send_text(json.dumps({"event": "pong"}))
605
-
606
- elif action == "start-workflow":
607
- # Handle workflow execution directly via WebSocket
608
- await handle_workflow_via_websocket(websocket, message, os)
609
-
610
- else:
611
- await websocket.send_text(json.dumps({"event": "error", "error": f"Unknown action: {action}"}))
612
-
613
- except Exception as e:
614
- if "1012" not in str(e) and "1001" not in str(e):
615
- logger.error(f"WebSocket error: {e}")
616
- finally:
617
- # Clean up the websocket connection
618
- await websocket_manager.disconnect_websocket(websocket)
619
-
620
- return ws_router
621
-
622
-
623
38
  def get_base_router(
624
39
  os: "AgentOS",
625
40
  settings: AgnoAPISettings = AgnoAPISettings(),
@@ -792,1025 +207,6 @@ def get_base_router(
792
207
 
793
208
  return list(unique_models.values())
794
209
 
795
- # -- Agent routes ---
796
-
797
- @router.post(
798
- "/agents/{agent_id}/runs",
799
- tags=["Agents"],
800
- operation_id="create_agent_run",
801
- response_model_exclude_none=True,
802
- summary="Create Agent Run",
803
- description=(
804
- "Execute an agent with a message and optional media files. Supports both streaming and non-streaming responses.\n\n"
805
- "**Features:**\n"
806
- "- Text message input with optional session management\n"
807
- "- Multi-media support: images (PNG, JPEG, WebP), audio (WAV, MP3), video (MP4, WebM, etc.)\n"
808
- "- Document processing: PDF, CSV, DOCX, TXT, JSON\n"
809
- "- Real-time streaming responses with Server-Sent Events (SSE)\n"
810
- "- User and session context preservation\n\n"
811
- "**Streaming Response:**\n"
812
- "When `stream=true`, returns SSE events with `event` and `data` fields."
813
- ),
814
- responses={
815
- 200: {
816
- "description": "Agent run executed successfully",
817
- "content": {
818
- "text/event-stream": {
819
- "examples": {
820
- "event_stream": {
821
- "summary": "Example event stream response",
822
- "value": 'event: RunStarted\ndata: {"content": "Hello!", "run_id": "123..."}\n\n',
823
- }
824
- }
825
- },
826
- },
827
- },
828
- 400: {"description": "Invalid request or unsupported file type", "model": BadRequestResponse},
829
- 404: {"description": "Agent not found", "model": NotFoundResponse},
830
- },
831
- )
832
- async def create_agent_run(
833
- agent_id: str,
834
- request: Request,
835
- background_tasks: BackgroundTasks,
836
- message: str = Form(...),
837
- stream: bool = Form(False),
838
- session_id: Optional[str] = Form(None),
839
- user_id: Optional[str] = Form(None),
840
- files: Optional[List[UploadFile]] = File(None),
841
- ):
842
- kwargs = await _get_request_kwargs(request, create_agent_run)
843
-
844
- if hasattr(request.state, "user_id"):
845
- if user_id:
846
- log_warning("User ID parameter passed in both request state and kwargs, using request state")
847
- user_id = request.state.user_id
848
- if hasattr(request.state, "session_id"):
849
- if session_id:
850
- log_warning("Session ID parameter passed in both request state and kwargs, using request state")
851
- session_id = request.state.session_id
852
- if hasattr(request.state, "session_state"):
853
- session_state = request.state.session_state
854
- if "session_state" in kwargs:
855
- log_warning("Session state parameter passed in both request state and kwargs, using request state")
856
- kwargs["session_state"] = session_state
857
- if hasattr(request.state, "dependencies"):
858
- dependencies = request.state.dependencies
859
- if "dependencies" in kwargs:
860
- log_warning("Dependencies parameter passed in both request state and kwargs, using request state")
861
- kwargs["dependencies"] = dependencies
862
- if hasattr(request.state, "metadata"):
863
- metadata = request.state.metadata
864
- if "metadata" in kwargs:
865
- log_warning("Metadata parameter passed in both request state and kwargs, using request state")
866
- kwargs["metadata"] = metadata
867
-
868
- agent = get_agent_by_id(agent_id, os.agents)
869
- if agent is None:
870
- raise HTTPException(status_code=404, detail="Agent not found")
871
-
872
- if session_id is None or session_id == "":
873
- log_debug("Creating new session")
874
- session_id = str(uuid4())
875
-
876
- base64_images: List[Image] = []
877
- base64_audios: List[Audio] = []
878
- base64_videos: List[Video] = []
879
- input_files: List[FileMedia] = []
880
-
881
- if files:
882
- for file in files:
883
- if file.content_type in [
884
- "image/png",
885
- "image/jpeg",
886
- "image/jpg",
887
- "image/gif",
888
- "image/webp",
889
- "image/bmp",
890
- "image/tiff",
891
- "image/tif",
892
- "image/avif",
893
- ]:
894
- try:
895
- base64_image = process_image(file)
896
- base64_images.append(base64_image)
897
- except Exception as e:
898
- log_error(f"Error processing image {file.filename}: {e}")
899
- continue
900
- elif file.content_type in [
901
- "audio/wav",
902
- "audio/wave",
903
- "audio/mp3",
904
- "audio/mpeg",
905
- "audio/ogg",
906
- "audio/mp4",
907
- "audio/m4a",
908
- "audio/aac",
909
- "audio/flac",
910
- ]:
911
- try:
912
- audio = process_audio(file)
913
- base64_audios.append(audio)
914
- except Exception as e:
915
- log_error(f"Error processing audio {file.filename} with content type {file.content_type}: {e}")
916
- continue
917
- elif file.content_type in [
918
- "video/x-flv",
919
- "video/quicktime",
920
- "video/mpeg",
921
- "video/mpegs",
922
- "video/mpgs",
923
- "video/mpg",
924
- "video/mpg",
925
- "video/mp4",
926
- "video/webm",
927
- "video/wmv",
928
- "video/3gpp",
929
- ]:
930
- try:
931
- base64_video = process_video(file)
932
- base64_videos.append(base64_video)
933
- except Exception as e:
934
- log_error(f"Error processing video {file.filename}: {e}")
935
- continue
936
- elif file.content_type in [
937
- "application/pdf",
938
- "application/json",
939
- "application/x-javascript",
940
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
941
- "text/javascript",
942
- "application/x-python",
943
- "text/x-python",
944
- "text/plain",
945
- "text/html",
946
- "text/css",
947
- "text/md",
948
- "text/csv",
949
- "text/xml",
950
- "text/rtf",
951
- ]:
952
- # Process document files
953
- try:
954
- input_file = process_document(file)
955
- if input_file is not None:
956
- input_files.append(input_file)
957
- except Exception as e:
958
- log_error(f"Error processing file {file.filename}: {e}")
959
- continue
960
- else:
961
- raise HTTPException(status_code=400, detail="Unsupported file type")
962
-
963
- if stream:
964
- return StreamingResponse(
965
- agent_response_streamer(
966
- agent,
967
- message,
968
- session_id=session_id,
969
- user_id=user_id,
970
- images=base64_images if base64_images else None,
971
- audio=base64_audios if base64_audios else None,
972
- videos=base64_videos if base64_videos else None,
973
- files=input_files if input_files else None,
974
- background_tasks=background_tasks,
975
- **kwargs,
976
- ),
977
- media_type="text/event-stream",
978
- )
979
- else:
980
- try:
981
- run_response = cast(
982
- RunOutput,
983
- await agent.arun(
984
- input=message,
985
- session_id=session_id,
986
- user_id=user_id,
987
- images=base64_images if base64_images else None,
988
- audio=base64_audios if base64_audios else None,
989
- videos=base64_videos if base64_videos else None,
990
- files=input_files if input_files else None,
991
- stream=False,
992
- background_tasks=background_tasks,
993
- **kwargs,
994
- ),
995
- )
996
- return run_response.to_dict()
997
-
998
- except InputCheckError as e:
999
- raise HTTPException(status_code=400, detail=str(e))
1000
-
1001
- @router.post(
1002
- "/agents/{agent_id}/runs/{run_id}/cancel",
1003
- tags=["Agents"],
1004
- operation_id="cancel_agent_run",
1005
- response_model_exclude_none=True,
1006
- summary="Cancel Agent Run",
1007
- description=(
1008
- "Cancel a currently executing agent run. This will attempt to stop the agent's execution gracefully.\n\n"
1009
- "**Note:** Cancellation may not be immediate for all operations."
1010
- ),
1011
- responses={
1012
- 200: {},
1013
- 404: {"description": "Agent not found", "model": NotFoundResponse},
1014
- 500: {"description": "Failed to cancel run", "model": InternalServerErrorResponse},
1015
- },
1016
- )
1017
- async def cancel_agent_run(
1018
- agent_id: str,
1019
- run_id: str,
1020
- ):
1021
- agent = get_agent_by_id(agent_id, os.agents)
1022
- if agent is None:
1023
- raise HTTPException(status_code=404, detail="Agent not found")
1024
-
1025
- if not agent.cancel_run(run_id=run_id):
1026
- raise HTTPException(status_code=500, detail="Failed to cancel run")
1027
-
1028
- return JSONResponse(content={}, status_code=200)
1029
-
1030
- @router.post(
1031
- "/agents/{agent_id}/runs/{run_id}/continue",
1032
- tags=["Agents"],
1033
- operation_id="continue_agent_run",
1034
- response_model_exclude_none=True,
1035
- summary="Continue Agent Run",
1036
- description=(
1037
- "Continue a paused or incomplete agent run with updated tool results.\n\n"
1038
- "**Use Cases:**\n"
1039
- "- Resume execution after tool approval/rejection\n"
1040
- "- Provide manual tool execution results\n\n"
1041
- "**Tools Parameter:**\n"
1042
- "JSON string containing array of tool execution objects with results."
1043
- ),
1044
- responses={
1045
- 200: {
1046
- "description": "Agent run continued successfully",
1047
- "content": {
1048
- "text/event-stream": {
1049
- "example": 'event: RunContent\ndata: {"created_at": 1757348314, "run_id": "123..."}\n\n'
1050
- },
1051
- },
1052
- },
1053
- 400: {"description": "Invalid JSON in tools field or invalid tool structure", "model": BadRequestResponse},
1054
- 404: {"description": "Agent not found", "model": NotFoundResponse},
1055
- },
1056
- )
1057
- async def continue_agent_run(
1058
- agent_id: str,
1059
- run_id: str,
1060
- request: Request,
1061
- background_tasks: BackgroundTasks,
1062
- tools: str = Form(...), # JSON string of tools
1063
- session_id: Optional[str] = Form(None),
1064
- user_id: Optional[str] = Form(None),
1065
- stream: bool = Form(True),
1066
- ):
1067
- if hasattr(request.state, "user_id"):
1068
- user_id = request.state.user_id
1069
- if hasattr(request.state, "session_id"):
1070
- session_id = request.state.session_id
1071
-
1072
- # Parse the JSON string manually
1073
- try:
1074
- tools_data = json.loads(tools) if tools else None
1075
- except json.JSONDecodeError:
1076
- raise HTTPException(status_code=400, detail="Invalid JSON in tools field")
1077
-
1078
- agent = get_agent_by_id(agent_id, os.agents)
1079
- if agent is None:
1080
- raise HTTPException(status_code=404, detail="Agent not found")
1081
-
1082
- if session_id is None or session_id == "":
1083
- log_warning(
1084
- "Continuing run without session_id. This might lead to unexpected behavior if session context is important."
1085
- )
1086
-
1087
- # Convert tools dict to ToolExecution objects if provided
1088
- updated_tools = None
1089
- if tools_data:
1090
- try:
1091
- from agno.models.response import ToolExecution
1092
-
1093
- updated_tools = [ToolExecution.from_dict(tool) for tool in tools_data]
1094
- except Exception as e:
1095
- raise HTTPException(status_code=400, detail=f"Invalid structure or content for tools: {str(e)}")
1096
-
1097
- if stream:
1098
- return StreamingResponse(
1099
- agent_continue_response_streamer(
1100
- agent,
1101
- run_id=run_id, # run_id from path
1102
- updated_tools=updated_tools,
1103
- session_id=session_id,
1104
- user_id=user_id,
1105
- background_tasks=background_tasks,
1106
- ),
1107
- media_type="text/event-stream",
1108
- )
1109
- else:
1110
- try:
1111
- run_response_obj = cast(
1112
- RunOutput,
1113
- await agent.acontinue_run(
1114
- run_id=run_id, # run_id from path
1115
- updated_tools=updated_tools,
1116
- session_id=session_id,
1117
- user_id=user_id,
1118
- stream=False,
1119
- background_tasks=background_tasks,
1120
- ),
1121
- )
1122
- return run_response_obj.to_dict()
1123
-
1124
- except InputCheckError as e:
1125
- raise HTTPException(status_code=400, detail=str(e))
1126
-
1127
- @router.get(
1128
- "/agents",
1129
- response_model=List[AgentResponse],
1130
- response_model_exclude_none=True,
1131
- tags=["Agents"],
1132
- operation_id="get_agents",
1133
- summary="List All Agents",
1134
- description=(
1135
- "Retrieve a comprehensive list of all agents configured in this OS instance.\n\n"
1136
- "**Returns:**\n"
1137
- "- Agent metadata (ID, name, description)\n"
1138
- "- Model configuration and capabilities\n"
1139
- "- Available tools and their configurations\n"
1140
- "- Session, knowledge, memory, and reasoning settings\n"
1141
- "- Only meaningful (non-default) configurations are included"
1142
- ),
1143
- responses={
1144
- 200: {
1145
- "description": "List of agents retrieved successfully",
1146
- "content": {
1147
- "application/json": {
1148
- "example": [
1149
- {
1150
- "id": "main-agent",
1151
- "name": "Main Agent",
1152
- "db_id": "c6bf0644-feb8-4930-a305-380dae5ad6aa",
1153
- "model": {"name": "OpenAIChat", "model": "gpt-4o", "provider": "OpenAI"},
1154
- "tools": None,
1155
- "sessions": {"session_table": "agno_sessions"},
1156
- "knowledge": {"knowledge_table": "main_knowledge"},
1157
- "system_message": {"markdown": True, "add_datetime_to_context": True},
1158
- }
1159
- ]
1160
- }
1161
- },
1162
- }
1163
- },
1164
- )
1165
- async def get_agents() -> List[AgentResponse]:
1166
- """Return the list of all Agents present in the contextual OS"""
1167
- if os.agents is None:
1168
- return []
1169
-
1170
- agents = []
1171
- for agent in os.agents:
1172
- agent_response = await AgentResponse.from_agent(agent=agent)
1173
- agents.append(agent_response)
1174
-
1175
- return agents
1176
-
1177
- @router.get(
1178
- "/agents/{agent_id}",
1179
- response_model=AgentResponse,
1180
- response_model_exclude_none=True,
1181
- tags=["Agents"],
1182
- operation_id="get_agent",
1183
- summary="Get Agent Details",
1184
- description=(
1185
- "Retrieve detailed configuration and capabilities of a specific agent.\n\n"
1186
- "**Returns comprehensive agent information including:**\n"
1187
- "- Model configuration and provider details\n"
1188
- "- Complete tool inventory and configurations\n"
1189
- "- Session management settings\n"
1190
- "- Knowledge base and memory configurations\n"
1191
- "- Reasoning capabilities and settings\n"
1192
- "- System prompts and response formatting options"
1193
- ),
1194
- responses={
1195
- 200: {
1196
- "description": "Agent details retrieved successfully",
1197
- "content": {
1198
- "application/json": {
1199
- "example": {
1200
- "id": "main-agent",
1201
- "name": "Main Agent",
1202
- "db_id": "9e064c70-6821-4840-a333-ce6230908a70",
1203
- "model": {"name": "OpenAIChat", "model": "gpt-4o", "provider": "OpenAI"},
1204
- "tools": None,
1205
- "sessions": {"session_table": "agno_sessions"},
1206
- "knowledge": {"knowledge_table": "main_knowledge"},
1207
- "system_message": {"markdown": True, "add_datetime_to_context": True},
1208
- }
1209
- }
1210
- },
1211
- },
1212
- 404: {"description": "Agent not found", "model": NotFoundResponse},
1213
- },
1214
- )
1215
- async def get_agent(agent_id: str) -> AgentResponse:
1216
- agent = get_agent_by_id(agent_id, os.agents)
1217
- if agent is None:
1218
- raise HTTPException(status_code=404, detail="Agent not found")
1219
-
1220
- return await AgentResponse.from_agent(agent)
1221
-
1222
- # -- Team routes ---
1223
-
1224
- @router.post(
1225
- "/teams/{team_id}/runs",
1226
- tags=["Teams"],
1227
- operation_id="create_team_run",
1228
- response_model_exclude_none=True,
1229
- summary="Create Team Run",
1230
- description=(
1231
- "Execute a team collaboration with multiple agents working together on a task.\n\n"
1232
- "**Features:**\n"
1233
- "- Text message input with optional session management\n"
1234
- "- Multi-media support: images (PNG, JPEG, WebP), audio (WAV, MP3), video (MP4, WebM, etc.)\n"
1235
- "- Document processing: PDF, CSV, DOCX, TXT, JSON\n"
1236
- "- Real-time streaming responses with Server-Sent Events (SSE)\n"
1237
- "- User and session context preservation\n\n"
1238
- "**Streaming Response:**\n"
1239
- "When `stream=true`, returns SSE events with `event` and `data` fields."
1240
- ),
1241
- responses={
1242
- 200: {
1243
- "description": "Team run executed successfully",
1244
- "content": {
1245
- "text/event-stream": {
1246
- "example": 'event: RunStarted\ndata: {"content": "Hello!", "run_id": "123..."}\n\n'
1247
- },
1248
- },
1249
- },
1250
- 400: {"description": "Invalid request or unsupported file type", "model": BadRequestResponse},
1251
- 404: {"description": "Team not found", "model": NotFoundResponse},
1252
- },
1253
- )
1254
- async def create_team_run(
1255
- team_id: str,
1256
- request: Request,
1257
- background_tasks: BackgroundTasks,
1258
- message: str = Form(...),
1259
- stream: bool = Form(True),
1260
- monitor: bool = Form(True),
1261
- session_id: Optional[str] = Form(None),
1262
- user_id: Optional[str] = Form(None),
1263
- files: Optional[List[UploadFile]] = File(None),
1264
- ):
1265
- kwargs = await _get_request_kwargs(request, create_team_run)
1266
-
1267
- if hasattr(request.state, "user_id"):
1268
- if user_id:
1269
- log_warning("User ID parameter passed in both request state and kwargs, using request state")
1270
- user_id = request.state.user_id
1271
- if hasattr(request.state, "session_id"):
1272
- if session_id:
1273
- log_warning("Session ID parameter passed in both request state and kwargs, using request state")
1274
- session_id = request.state.session_id
1275
- if hasattr(request.state, "session_state"):
1276
- session_state = request.state.session_state
1277
- if "session_state" in kwargs:
1278
- log_warning("Session state parameter passed in both request state and kwargs, using request state")
1279
- kwargs["session_state"] = session_state
1280
- if hasattr(request.state, "dependencies"):
1281
- dependencies = request.state.dependencies
1282
- if "dependencies" in kwargs:
1283
- log_warning("Dependencies parameter passed in both request state and kwargs, using request state")
1284
- kwargs["dependencies"] = dependencies
1285
- if hasattr(request.state, "metadata"):
1286
- metadata = request.state.metadata
1287
- if "metadata" in kwargs:
1288
- log_warning("Metadata parameter passed in both request state and kwargs, using request state")
1289
- kwargs["metadata"] = metadata
1290
-
1291
- logger.debug(f"Creating team run: {message=} {session_id=} {monitor=} {user_id=} {team_id=} {files=} {kwargs=}")
1292
-
1293
- team = get_team_by_id(team_id, os.teams)
1294
- if team is None:
1295
- raise HTTPException(status_code=404, detail="Team not found")
1296
-
1297
- if session_id is not None and session_id != "":
1298
- logger.debug(f"Continuing session: {session_id}")
1299
- else:
1300
- logger.debug("Creating new session")
1301
- session_id = str(uuid4())
1302
-
1303
- base64_images: List[Image] = []
1304
- base64_audios: List[Audio] = []
1305
- base64_videos: List[Video] = []
1306
- document_files: List[FileMedia] = []
1307
-
1308
- if files:
1309
- for file in files:
1310
- if file.content_type in ["image/png", "image/jpeg", "image/jpg", "image/webp"]:
1311
- try:
1312
- base64_image = process_image(file)
1313
- base64_images.append(base64_image)
1314
- except Exception as e:
1315
- logger.error(f"Error processing image {file.filename}: {e}")
1316
- continue
1317
- elif file.content_type in ["audio/wav", "audio/mp3", "audio/mpeg"]:
1318
- try:
1319
- base64_audio = process_audio(file)
1320
- base64_audios.append(base64_audio)
1321
- except Exception as e:
1322
- logger.error(f"Error processing audio {file.filename}: {e}")
1323
- continue
1324
- elif file.content_type in [
1325
- "video/x-flv",
1326
- "video/quicktime",
1327
- "video/mpeg",
1328
- "video/mpegs",
1329
- "video/mpgs",
1330
- "video/mpg",
1331
- "video/mpg",
1332
- "video/mp4",
1333
- "video/webm",
1334
- "video/wmv",
1335
- "video/3gpp",
1336
- ]:
1337
- try:
1338
- base64_video = process_video(file)
1339
- base64_videos.append(base64_video)
1340
- except Exception as e:
1341
- logger.error(f"Error processing video {file.filename}: {e}")
1342
- continue
1343
- elif file.content_type in [
1344
- "application/pdf",
1345
- "text/csv",
1346
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
1347
- "text/plain",
1348
- "application/json",
1349
- ]:
1350
- document_file = process_document(file)
1351
- if document_file is not None:
1352
- document_files.append(document_file)
1353
- else:
1354
- raise HTTPException(status_code=400, detail="Unsupported file type")
1355
-
1356
- if stream:
1357
- return StreamingResponse(
1358
- team_response_streamer(
1359
- team,
1360
- message,
1361
- session_id=session_id,
1362
- user_id=user_id,
1363
- images=base64_images if base64_images else None,
1364
- audio=base64_audios if base64_audios else None,
1365
- videos=base64_videos if base64_videos else None,
1366
- files=document_files if document_files else None,
1367
- background_tasks=background_tasks,
1368
- **kwargs,
1369
- ),
1370
- media_type="text/event-stream",
1371
- )
1372
- else:
1373
- try:
1374
- run_response = await team.arun(
1375
- input=message,
1376
- session_id=session_id,
1377
- user_id=user_id,
1378
- images=base64_images if base64_images else None,
1379
- audio=base64_audios if base64_audios else None,
1380
- videos=base64_videos if base64_videos else None,
1381
- files=document_files if document_files else None,
1382
- stream=False,
1383
- background_tasks=background_tasks,
1384
- **kwargs,
1385
- )
1386
- return run_response.to_dict()
1387
-
1388
- except InputCheckError as e:
1389
- raise HTTPException(status_code=400, detail=str(e))
1390
-
1391
- @router.post(
1392
- "/teams/{team_id}/runs/{run_id}/cancel",
1393
- tags=["Teams"],
1394
- operation_id="cancel_team_run",
1395
- response_model_exclude_none=True,
1396
- summary="Cancel Team Run",
1397
- description=(
1398
- "Cancel a currently executing team run. This will attempt to stop the team's execution gracefully.\n\n"
1399
- "**Note:** Cancellation may not be immediate for all operations."
1400
- ),
1401
- responses={
1402
- 200: {},
1403
- 404: {"description": "Team not found", "model": NotFoundResponse},
1404
- 500: {"description": "Failed to cancel team run", "model": InternalServerErrorResponse},
1405
- },
1406
- )
1407
- async def cancel_team_run(
1408
- team_id: str,
1409
- run_id: str,
1410
- ):
1411
- team = get_team_by_id(team_id, os.teams)
1412
- if team is None:
1413
- raise HTTPException(status_code=404, detail="Team not found")
1414
-
1415
- if not team.cancel_run(run_id=run_id):
1416
- raise HTTPException(status_code=500, detail="Failed to cancel run")
1417
-
1418
- return JSONResponse(content={}, status_code=200)
1419
-
1420
- @router.get(
1421
- "/teams",
1422
- response_model=List[TeamResponse],
1423
- response_model_exclude_none=True,
1424
- tags=["Teams"],
1425
- operation_id="get_teams",
1426
- summary="List All Teams",
1427
- description=(
1428
- "Retrieve a comprehensive list of all teams configured in this OS instance.\n\n"
1429
- "**Returns team information including:**\n"
1430
- "- Team metadata (ID, name, description, execution mode)\n"
1431
- "- Model configuration for team coordination\n"
1432
- "- Team member roster with roles and capabilities\n"
1433
- "- Knowledge sharing and memory configurations"
1434
- ),
1435
- responses={
1436
- 200: {
1437
- "description": "List of teams retrieved successfully",
1438
- "content": {
1439
- "application/json": {
1440
- "example": [
1441
- {
1442
- "team_id": "basic-team",
1443
- "name": "Basic Team",
1444
- "mode": "coordinate",
1445
- "model": {"name": "OpenAIChat", "model": "gpt-4o", "provider": "OpenAI"},
1446
- "tools": [
1447
- {
1448
- "name": "transfer_task_to_member",
1449
- "description": "Use this function to transfer a task to the selected team member.\nYou must provide a clear and concise description of the task the member should achieve AND the expected output.",
1450
- "parameters": {
1451
- "type": "object",
1452
- "properties": {
1453
- "member_id": {
1454
- "type": "string",
1455
- "description": "(str) The ID of the member to transfer the task to. Use only the ID of the member, not the ID of the team followed by the ID of the member.",
1456
- },
1457
- "task_description": {
1458
- "type": "string",
1459
- "description": "(str) A clear and concise description of the task the member should achieve.",
1460
- },
1461
- "expected_output": {
1462
- "type": "string",
1463
- "description": "(str) The expected output from the member (optional).",
1464
- },
1465
- },
1466
- "additionalProperties": False,
1467
- "required": ["member_id", "task_description"],
1468
- },
1469
- }
1470
- ],
1471
- "members": [
1472
- {
1473
- "agent_id": "basic-agent",
1474
- "name": "Basic Agent",
1475
- "model": {"name": "OpenAIChat", "model": "gpt-4o", "provider": "OpenAI gpt-4o"},
1476
- "memory": {
1477
- "app_name": "Memory",
1478
- "app_url": None,
1479
- "model": {"name": "OpenAIChat", "model": "gpt-4o", "provider": "OpenAI"},
1480
- },
1481
- "session_table": "agno_sessions",
1482
- "memory_table": "agno_memories",
1483
- }
1484
- ],
1485
- "enable_agentic_context": False,
1486
- "memory": {
1487
- "app_name": "agno_memories",
1488
- "app_url": "/memory/1",
1489
- "model": {"name": "OpenAIChat", "model": "gpt-4o", "provider": "OpenAI"},
1490
- },
1491
- "async_mode": False,
1492
- "session_table": "agno_sessions",
1493
- "memory_table": "agno_memories",
1494
- }
1495
- ]
1496
- }
1497
- },
1498
- }
1499
- },
1500
- )
1501
- async def get_teams() -> List[TeamResponse]:
1502
- """Return the list of all Teams present in the contextual OS"""
1503
- if os.teams is None:
1504
- return []
1505
-
1506
- teams = []
1507
- for team in os.teams:
1508
- team_response = await TeamResponse.from_team(team=team)
1509
- teams.append(team_response)
1510
-
1511
- return teams
1512
-
1513
- @router.get(
1514
- "/teams/{team_id}",
1515
- response_model=TeamResponse,
1516
- response_model_exclude_none=True,
1517
- tags=["Teams"],
1518
- operation_id="get_team",
1519
- summary="Get Team Details",
1520
- description=("Retrieve detailed configuration and member information for a specific team."),
1521
- responses={
1522
- 200: {
1523
- "description": "Team details retrieved successfully",
1524
- "content": {
1525
- "application/json": {
1526
- "example": {
1527
- "team_id": "basic-team",
1528
- "name": "Basic Team",
1529
- "description": None,
1530
- "mode": "coordinate",
1531
- "model": {"name": "OpenAIChat", "model": "gpt-4o", "provider": "OpenAI"},
1532
- "tools": [
1533
- {
1534
- "name": "transfer_task_to_member",
1535
- "description": "Use this function to transfer a task to the selected team member.\nYou must provide a clear and concise description of the task the member should achieve AND the expected output.",
1536
- "parameters": {
1537
- "type": "object",
1538
- "properties": {
1539
- "member_id": {
1540
- "type": "string",
1541
- "description": "(str) The ID of the member to transfer the task to. Use only the ID of the member, not the ID of the team followed by the ID of the member.",
1542
- },
1543
- "task_description": {
1544
- "type": "string",
1545
- "description": "(str) A clear and concise description of the task the member should achieve.",
1546
- },
1547
- "expected_output": {
1548
- "type": "string",
1549
- "description": "(str) The expected output from the member (optional).",
1550
- },
1551
- },
1552
- "additionalProperties": False,
1553
- "required": ["member_id", "task_description"],
1554
- },
1555
- }
1556
- ],
1557
- "instructions": None,
1558
- "members": [
1559
- {
1560
- "agent_id": "basic-agent",
1561
- "name": "Basic Agent",
1562
- "description": None,
1563
- "instructions": None,
1564
- "model": {"name": "OpenAIChat", "model": "gpt-4o", "provider": "OpenAI gpt-4o"},
1565
- "tools": None,
1566
- "memory": {
1567
- "app_name": "Memory",
1568
- "app_url": None,
1569
- "model": {"name": "OpenAIChat", "model": "gpt-4o", "provider": "OpenAI"},
1570
- },
1571
- "knowledge": None,
1572
- "session_table": "agno_sessions",
1573
- "memory_table": "agno_memories",
1574
- "knowledge_table": None,
1575
- }
1576
- ],
1577
- "expected_output": None,
1578
- "dependencies": None,
1579
- "enable_agentic_context": False,
1580
- "memory": {
1581
- "app_name": "Memory",
1582
- "app_url": None,
1583
- "model": {"name": "OpenAIChat", "model": "gpt-4o", "provider": "OpenAI"},
1584
- },
1585
- "knowledge": None,
1586
- "async_mode": False,
1587
- "session_table": "agno_sessions",
1588
- "memory_table": "agno_memories",
1589
- "knowledge_table": None,
1590
- }
1591
- }
1592
- },
1593
- },
1594
- 404: {"description": "Team not found", "model": NotFoundResponse},
1595
- },
1596
- )
1597
- async def get_team(team_id: str) -> TeamResponse:
1598
- team = get_team_by_id(team_id, os.teams)
1599
- if team is None:
1600
- raise HTTPException(status_code=404, detail="Team not found")
1601
-
1602
- return await TeamResponse.from_team(team)
1603
-
1604
- # -- Workflow routes ---
1605
-
1606
- @router.get(
1607
- "/workflows",
1608
- response_model=List[WorkflowSummaryResponse],
1609
- response_model_exclude_none=True,
1610
- tags=["Workflows"],
1611
- operation_id="get_workflows",
1612
- summary="List All Workflows",
1613
- description=(
1614
- "Retrieve a comprehensive list of all workflows configured in this OS instance.\n\n"
1615
- "**Return Information:**\n"
1616
- "- Workflow metadata (ID, name, description)\n"
1617
- "- Input schema requirements\n"
1618
- "- Step sequence and execution flow\n"
1619
- "- Associated agents and teams"
1620
- ),
1621
- responses={
1622
- 200: {
1623
- "description": "List of workflows retrieved successfully",
1624
- "content": {
1625
- "application/json": {
1626
- "example": [
1627
- {
1628
- "id": "content-creation-workflow",
1629
- "name": "Content Creation Workflow",
1630
- "description": "Automated content creation from blog posts to social media",
1631
- "db_id": "123",
1632
- }
1633
- ]
1634
- }
1635
- },
1636
- }
1637
- },
1638
- )
1639
- async def get_workflows() -> List[WorkflowSummaryResponse]:
1640
- if os.workflows is None:
1641
- return []
1642
-
1643
- return [WorkflowSummaryResponse.from_workflow(workflow) for workflow in os.workflows]
1644
-
1645
- @router.get(
1646
- "/workflows/{workflow_id}",
1647
- response_model=WorkflowResponse,
1648
- response_model_exclude_none=True,
1649
- tags=["Workflows"],
1650
- operation_id="get_workflow",
1651
- summary="Get Workflow Details",
1652
- description=("Retrieve detailed configuration and step information for a specific workflow."),
1653
- responses={
1654
- 200: {
1655
- "description": "Workflow details retrieved successfully",
1656
- "content": {
1657
- "application/json": {
1658
- "example": {
1659
- "id": "content-creation-workflow",
1660
- "name": "Content Creation Workflow",
1661
- "description": "Automated content creation from blog posts to social media",
1662
- "db_id": "123",
1663
- }
1664
- }
1665
- },
1666
- },
1667
- 404: {"description": "Workflow not found", "model": NotFoundResponse},
1668
- },
1669
- )
1670
- async def get_workflow(workflow_id: str) -> WorkflowResponse:
1671
- workflow = get_workflow_by_id(workflow_id, os.workflows)
1672
- if workflow is None:
1673
- raise HTTPException(status_code=404, detail="Workflow not found")
1674
-
1675
- return await WorkflowResponse.from_workflow(workflow)
1676
-
1677
- @router.post(
1678
- "/workflows/{workflow_id}/runs",
1679
- tags=["Workflows"],
1680
- operation_id="create_workflow_run",
1681
- response_model_exclude_none=True,
1682
- summary="Execute Workflow",
1683
- description=(
1684
- "Execute a workflow with the provided input data. Workflows can run in streaming or batch mode.\n\n"
1685
- "**Execution Modes:**\n"
1686
- "- **Streaming (`stream=true`)**: Real-time step-by-step execution updates via SSE\n"
1687
- "- **Non-Streaming (`stream=false`)**: Complete workflow execution with final result\n\n"
1688
- "**Workflow Execution Process:**\n"
1689
- "1. Input validation against workflow schema\n"
1690
- "2. Sequential or parallel step execution based on workflow design\n"
1691
- "3. Data flow between steps with transformation\n"
1692
- "4. Error handling and automatic retries where configured\n"
1693
- "5. Final result compilation and response\n\n"
1694
- "**Session Management:**\n"
1695
- "Workflows support session continuity for stateful execution across multiple runs."
1696
- ),
1697
- responses={
1698
- 200: {
1699
- "description": "Workflow executed successfully",
1700
- "content": {
1701
- "text/event-stream": {
1702
- "example": 'event: RunStarted\ndata: {"content": "Hello!", "run_id": "123..."}\n\n'
1703
- },
1704
- },
1705
- },
1706
- 400: {"description": "Invalid input data or workflow configuration", "model": BadRequestResponse},
1707
- 404: {"description": "Workflow not found", "model": NotFoundResponse},
1708
- 500: {"description": "Workflow execution error", "model": InternalServerErrorResponse},
1709
- },
1710
- )
1711
- async def create_workflow_run(
1712
- workflow_id: str,
1713
- request: Request,
1714
- background_tasks: BackgroundTasks,
1715
- message: str = Form(...),
1716
- stream: bool = Form(True),
1717
- session_id: Optional[str] = Form(None),
1718
- user_id: Optional[str] = Form(None),
1719
- ):
1720
- kwargs = await _get_request_kwargs(request, create_workflow_run)
1721
-
1722
- if hasattr(request.state, "user_id"):
1723
- if user_id:
1724
- log_warning("User ID parameter passed in both request state and kwargs, using request state")
1725
- user_id = request.state.user_id
1726
- if hasattr(request.state, "session_id"):
1727
- if session_id:
1728
- log_warning("Session ID parameter passed in both request state and kwargs, using request state")
1729
- session_id = request.state.session_id
1730
- if hasattr(request.state, "session_state"):
1731
- session_state = request.state.session_state
1732
- if "session_state" in kwargs:
1733
- log_warning("Session state parameter passed in both request state and kwargs, using request state")
1734
- kwargs["session_state"] = session_state
1735
- if hasattr(request.state, "dependencies"):
1736
- dependencies = request.state.dependencies
1737
- if "dependencies" in kwargs:
1738
- log_warning("Dependencies parameter passed in both request state and kwargs, using request state")
1739
- kwargs["dependencies"] = dependencies
1740
- if hasattr(request.state, "metadata"):
1741
- metadata = request.state.metadata
1742
- if "metadata" in kwargs:
1743
- log_warning("Metadata parameter passed in both request state and kwargs, using request state")
1744
- kwargs["metadata"] = metadata
1745
-
1746
- # Retrieve the workflow by ID
1747
- workflow = get_workflow_by_id(workflow_id, os.workflows)
1748
- if workflow is None:
1749
- raise HTTPException(status_code=404, detail="Workflow not found")
1750
-
1751
- if session_id:
1752
- logger.debug(f"Continuing session: {session_id}")
1753
- else:
1754
- logger.debug("Creating new session")
1755
- session_id = str(uuid4())
1756
-
1757
- # Return based on stream parameter
1758
- try:
1759
- if stream:
1760
- return StreamingResponse(
1761
- workflow_response_streamer(
1762
- workflow,
1763
- input=message,
1764
- session_id=session_id,
1765
- user_id=user_id,
1766
- background_tasks=background_tasks,
1767
- **kwargs,
1768
- ),
1769
- media_type="text/event-stream",
1770
- )
1771
- else:
1772
- run_response = await workflow.arun(
1773
- input=message,
1774
- session_id=session_id,
1775
- user_id=user_id,
1776
- stream=False,
1777
- background_tasks=background_tasks,
1778
- **kwargs,
1779
- )
1780
- return run_response.to_dict()
1781
-
1782
- except InputCheckError as e:
1783
- raise HTTPException(status_code=400, detail=str(e))
1784
- except Exception as e:
1785
- # Handle unexpected runtime errors
1786
- raise HTTPException(status_code=500, detail=f"Error running workflow: {str(e)}")
1787
-
1788
- @router.post(
1789
- "/workflows/{workflow_id}/runs/{run_id}/cancel",
1790
- tags=["Workflows"],
1791
- operation_id="cancel_workflow_run",
1792
- summary="Cancel Workflow Run",
1793
- description=(
1794
- "Cancel a currently executing workflow run, stopping all active steps and cleanup.\n"
1795
- "**Note:** Complex workflows with multiple parallel steps may take time to fully cancel."
1796
- ),
1797
- responses={
1798
- 200: {},
1799
- 404: {"description": "Workflow or run not found", "model": NotFoundResponse},
1800
- 500: {"description": "Failed to cancel workflow run", "model": InternalServerErrorResponse},
1801
- },
1802
- )
1803
- async def cancel_workflow_run(workflow_id: str, run_id: str):
1804
- workflow = get_workflow_by_id(workflow_id, os.workflows)
1805
-
1806
- if workflow is None:
1807
- raise HTTPException(status_code=404, detail="Workflow not found")
1808
-
1809
- if not workflow.cancel_run(run_id=run_id):
1810
- raise HTTPException(status_code=500, detail="Failed to cancel run")
1811
-
1812
- return JSONResponse(content={}, status_code=200)
1813
-
1814
210
  # -- Database Migration routes ---
1815
211
 
1816
212
  @router.post(