-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudit.txt
More file actions
3391 lines (2884 loc) · 137 KB
/
audit.txt
File metadata and controls
3391 lines (2884 loc) · 137 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
================================================================================
AXON REPOSITORY FULL AUDIT REPORT
================================================================================
Generated: 2026-03-14
Scope: backend/ and agents/ directories
Purpose: Complete system analysis and architecture documentation
================================================================================
1. SYSTEM OVERVIEW
================================================================================
AXON is a multi-agent AI orchestration platform built on FastAPI that
coordinates specialized agents to execute complex tasks through a pipeline
architecture. The system integrates with DigitalOcean's Gradient AI Platform
for LLM inference and agent deployment.
Core Architecture:
- Backend: FastAPI-based orchestration layer with PostgreSQL persistence
- Agents: Four specialized ADK agents deployed on DigitalOcean infrastructure
- Memory: ChromaDB vector store for semantic memory and context retrieval
- Skills: Pluggable execution modules for agent capabilities
- Evolution: Self-improving system that generates new skills from failures
Operating Modes:
- mock: Local testing with simulated LLM responses
- real: Production mode routing all inference through deployed ADK agents
Technology Stack:
- Backend: Python 3.11+, FastAPI, SQLAlchemy 2.0, AsyncPG
- Agents: gradient-adk, LangGraph, Gradient SDK
- Database: PostgreSQL with async support
- Vector Store: ChromaDB with sentence-transformers embeddings
- Observability: Loguru structured logging, WebSocket event streaming
================================================================================
2. FULL DIRECTORY STRUCTURE
================================================================================
backend/
├── .chroma/
│ └── chroma.sqlite3 # Vector database persistence
├── .pytest_cache/ # Test cache
├── .venv/ # Python virtual environment
├── alembic/ # Database migrations
│ ├── versions/
│ │ └── 0001_initial.py # Initial schema migration
│ └── env.py # Alembic configuration
├── scripts/
│ ├── dev_test.py # Development testing utilities
│ ├── evaluation_dataset_example.csv # Agent evaluation dataset
│ └── run_agent_evaluation.py # Automated evaluation runner
├── src/
│ ├── agents/ # Agent implementations
│ │ ├── base_agent.py # Abstract base agent class
│ │ ├── planning_agent.py # Task planning agent
│ │ ├── research_agent.py # Research and information gathering
│ │ ├── reasoning_agent.py # Strategy evaluation agent
│ │ └── builder_agent.py # Solution generation agent
│ ├── ai/ # LLM service layer
│ │ ├── llm_service.py # Unified LLM interface
│ │ ├── gradient_client.py # DigitalOcean Gradient client
│ │ └── huggingface_client.py # HuggingFace inference client
│ ├── api/ # HTTP API layer
│ │ ├── controllers/
│ │ │ ├── task_controller.py # Task CRUD operations
│ │ │ ├── skill_controller.py # Skill listing
│ │ │ └── evolution_controller.py # Evolution triggers
│ │ ├── middleware/
│ │ │ └── logging_middleware.py # HTTP request logging
│ │ ├── routes/
│ │ │ ├── tasks.py # Task endpoints
│ │ │ ├── skills.py # Skill endpoints
│ │ │ ├── evolution.py # Evolution endpoints
│ │ │ └── system.py # System status endpoints
│ │ └── websocket/
│ │ └── event_stream.py # Real-time event streaming
│ ├── config/
│ │ ├── config.py # Settings and environment variables
│ │ ├── agents_config.py # Agent URL configuration
│ │ └── dependencies.py # FastAPI dependency injection
│ ├── core/
│ │ ├── agent_orchestrator.py # Multi-agent pipeline coordinator
│ │ ├── task_manager.py # Async task queue manager
│ │ ├── event_bus.py # Pub/sub event system
│ │ ├── evolution_engine.py # Skill generation engine
│ │ ├── version_manager.py # Version control utilities
│ │ └── debug_tools.py # Debugging utilities
│ ├── db/
│ │ ├── models.py # SQLAlchemy ORM models
│ │ └── session.py # Database session management
│ ├── memory/
│ │ ├── vector_store.py # ChromaDB vector operations
│ │ └── embeddings.py # Sentence transformer embeddings
│ ├── providers/
│ │ └── digitalocean/
│ │ ├── digitalocean_agent_router.py # Agent routing logic
│ │ ├── digitalocean_agent_client.py # HTTP client for agents
│ │ └── digitalocean_agent_types.py # Request/response types
│ ├── schemas/
│ │ ├── task.py # Task Pydantic models
│ │ ├── skill.py # Skill Pydantic models
│ │ ├── evolution.py # Evolution Pydantic models
│ │ └── system.py # System status models
│ ├── services/
│ │ ├── task_service.py # Task business logic
│ │ ├── skill_service.py # Skill business logic
│ │ └── evolution_service.py # Evolution business logic
│ ├── skills/
│ │ ├── core_skills/
│ │ │ ├── planning.py # Planning skill implementation
│ │ │ ├── coding.py # Code generation skill
│ │ │ └── reasoning.py # Reasoning skill
│ │ ├── generated_skills/
│ │ │ └── web_search.py # Generated web search skill
│ │ ├── templates/
│ │ │ └── skill_template.py # Skill template
│ │ ├── registry.py # Skill discovery and registration
│ │ └── executor.py # Skill execution engine
│ ├── storage/
│ │ └── artifact_store.py # File artifact storage
│ ├── utils/
│ │ ├── logger.py # Loguru configuration
│ │ ├── audit_logger.py # Runtime audit generation
│ │ ├── validators.py # Input validation
│ │ └── code_parser.py # Code parsing utilities
│ └── main.py # FastAPI application entrypoint
├── tests/
│ ├── conftest.py # Pytest configuration
│ ├── test_agent_pipeline.py # Agent orchestration tests
│ ├── test_api_tasks.py # API endpoint tests
│ └── test_task_service.py # Service layer tests
├── .env.example # Environment variable template
├── alembic.ini # Alembic configuration
├── pyproject.toml # Project dependencies
└── audit.log # Runtime audit log
agents/
├── planner_agent/
│ ├── main.py # Planner agent implementation
│ ├── requirements.txt # Agent dependencies
│ └── .env.example # Agent environment template
├── research_agent/
│ ├── main.py # Research agent implementation
│ ├── requirements.txt # Agent dependencies
│ └── .env.example # Agent environment template
├── reasoning_agent/
│ ├── main.py # Reasoning agent implementation
│ ├── requirements.txt # Agent dependencies
│ └── .env.example # Agent environment template
├── builder_agent/
│ ├── main.py # Builder agent implementation
│ ├── requirements.txt # Agent dependencies
│ └── .env.example # Agent environment template
└── README.md # Agent deployment documentation
================================================================================
3. MODULE INDEX
================================================================================
────────────────────────────────────────────────────────────────────────────
BACKEND CORE MODULES
────────────────────────────────────────────────────────────────────────────
File: backend/src/main.py
Purpose: FastAPI application entrypoint with lifespan management
Key Components:
- FastAPI app initialization
- CORS middleware configuration
- Route registration (tasks, skills, evolution, system, websocket)
- Database initialization on startup
- TaskManager lifecycle management
- Audit log generation in test mode
Dependencies:
Internal: config, db.session, api.routes, utils.logger, utils.audit_logger
External: fastapi, fastapi.middleware.cors
Execution Role: Application bootstrap and HTTP server configuration
────────────────────────────────────────────────────────────────────────────
File: backend/src/core/agent_orchestrator.py
Purpose: Coordinates multi-agent pipeline execution for task processing
Key Classes:
- AgentOrchestrator
Methods:
- run_pipeline(task, session): Executes 4-stage agent pipeline
- _record_step(session, task, agent_name, input, output): Persists execution
Dependencies:
Internal: agents.*, ai.llm_service, memory.vector_store, core.event_bus,
providers.digitalocean.digitalocean_agent_router, db.models
External: sqlalchemy, time.perf_counter
Execution Role: Central orchestration hub for agent coordination
Pipeline Stages: Planning → Research → Reasoning → Builder
Performance: Tracks execution time per agent with microsecond precision
────────────────────────────────────────────────────────────────────────────
File: backend/src/core/task_manager.py
Purpose: Async task queue manager with background worker
Key Classes:
- TaskManager
Methods:
- start(): Launches background worker task
- stop(): Gracefully shuts down worker
- create_task(session, title, description): Enqueues new task
- list_tasks(session): Retrieves all tasks
- get_task(session, task_id): Retrieves single task
- run(): Background worker loop processing queue
- queue_size(): Returns pending task count
- status(): Returns worker status (running/stopped)
Dependencies:
Internal: core.agent_orchestrator, core.event_bus, db.models, db.session
External: asyncio, sqlalchemy, time.perf_counter
Execution Role: Manages async task execution queue with single worker
Concurrency: Single worker processes tasks sequentially
Error Handling: Catches exceptions, marks tasks as failed, continues processing
────────────────────────────────────────────────────────────────────────────
File: backend/src/core/event_bus.py
Purpose: Pub/sub event system for real-time notifications
Key Classes:
- EventBus
Methods:
- subscribe(callback): Registers event subscriber
- unsubscribe(callback): Removes event subscriber
- publish(event): Broadcasts event to all subscribers
- subscriber_count(): Returns active subscriber count
Dependencies:
Internal: None
External: asyncio
Execution Role: Decouples event producers from consumers
Thread Safety: Uses asyncio.Lock for subscriber list protection
Event Types: task.created, task.progress, task.result, task.error, agent.step
────────────────────────────────────────────────────────────────────────────
File: backend/src/core/evolution_engine.py
Purpose: Self-improving system that generates skills from failed tasks
Key Classes:
- EvolutionEngine
Methods:
- evolve(session): Analyzes failures and generates new skill
- get_status(session): Returns evolution statistics
- _sanitize_name(name): Cleans skill names for Python modules
- _failed_tasks_count(session): Counts failed tasks
Dependencies:
Internal: ai.llm_service, skills.registry, core.event_bus, db.models
External: sqlalchemy, importlib, re, datetime
Execution Role: Automated skill generation from failure patterns
Algorithm:
1. Count failed tasks
2. Generate skill description via LLM
3. Create Python module with SKILL metadata
4. Write to generated_skills/ directory
5. Reload skill registry
6. Persist to database
7. Emit evolution.generated event
────────────────────────────────────────────────────────────────────────────
AGENT IMPLEMENTATIONS
────────────────────────────────────────────────────────────────────────────
File: backend/src/agents/base_agent.py
Purpose: Abstract base class for all agent implementations
Key Classes:
- BaseAgent (ABC)
Attributes:
- agent_name: Agent identifier
- llm: LLM service instance
- skills: Skill executor instance
- memory: Vector store instance
- event_bus: Event bus instance
- digitalocean_router: Optional ADK agent router
Methods:
- _load_context(task_text, task_id): Retrieves semantic context
- _remember(task_id, content, memory_type): Stores memory
- _emit(event_type, payload): Publishes event
- execute(task): Abstract method for agent execution
Dependencies:
Internal: ai.llm_service, skills.executor, memory.vector_store,
core.event_bus, providers.digitalocean
External: abc
Execution Role: Provides common functionality for all agents
────────────────────────────────────────────────────────────────────────────
File: backend/src/agents/planning_agent.py
Purpose: Breaks down tasks into actionable steps
Key Classes:
- PlanningAgent(BaseAgent)
Methods:
- execute(task): Generates task plan
Execution Flow:
1. Load semantic context from vector store
2. If real mode: Route to DigitalOcean ADK planner agent
3. If mock mode: Execute planning skill + LLM refinement
4. Store result in memory
5. Emit agent.step event
6. Return plan structure
Dependencies:
Internal: agents.base_agent, config.config
External: json
Input Schema: {"id": str, "title": str, "description": str}
Output Schema: {"agent": "planning", "plan": dict, "llm_refinement": str}
────────────────────────────────────────────────────────────────────────────
File: backend/src/agents/research_agent.py
Purpose: Conducts research and gathers information
Key Classes:
- ResearchAgent(BaseAgent)
Methods:
- execute(task): Performs research
Execution Flow:
1. Load semantic context
2. If real mode: Route to ADK research agent (with KB retrieval)
3. If mock mode: Execute web_search skill + LLM synthesis
4. Store research in memory
5. Emit agent.step event
6. Return research notes
Dependencies:
Internal: agents.base_agent, config.config
External: json
Input Schema: {"id": str, "title": str, "description": str, "plan": dict}
Output Schema: {"agent": "research", "research": dict, "synthesis": str}
Special Features: Integrates with DigitalOcean Knowledge Base in real mode
────────────────────────────────────────────────────────────────────────────
File: backend/src/agents/reasoning_agent.py
Purpose: Evaluates strategies and provides logical analysis
Key Classes:
- ReasoningAgent(BaseAgent)
Methods:
- execute(task): Analyzes plan and provides reasoning
Execution Flow:
1. Load semantic context
2. If real mode: Route to ADK reasoning agent
3. If mock mode: Execute reasoning skill + LLM rationale
4. Store reasoning in memory
5. Emit agent.step event
6. Return analysis
Dependencies:
Internal: agents.base_agent, config.config
External: json
Input Schema: {"id": str, "title": str, "plan": dict}
Output Schema: {"agent": "reasoning", "analysis": dict, "rationale": str}
────────────────────────────────────────────────────────────────────────────
File: backend/src/agents/builder_agent.py
Purpose: Generates final solutions based on plan and reasoning
Key Classes:
- BuilderAgent(BaseAgent)
Methods:
- execute(task): Produces final solution
Execution Flow:
1. If real mode: Route to ADK builder agent
2. If mock mode: Execute coding skill + LLM response
3. Store build output in memory
4. Emit agent.step event
5. Return solution
Dependencies:
Internal: agents.base_agent, config.config
External: json
Input Schema: {"id": str, "title": str, "description": str, "plan": dict,
"reasoning": dict}
Output Schema: {"agent": "builder", "build": dict, "final": str}
────────────────────────────────────────────────────────────────────────────
AI SERVICE LAYER
────────────────────────────────────────────────────────────────────────────
File: backend/src/ai/llm_service.py
Purpose: Unified LLM interface with provider fallback chain
Key Classes:
- LLMService
Methods:
- complete(prompt): Single-turn completion
- chat(messages): Multi-turn conversation
- stream(messages): Streaming response generator
- _test_mode_response(messages): Deterministic mock responses
- _retry_call(func, *args, **kwargs): Retry logic with exponential backoff
- _extract_text(response): Normalizes provider responses
- _log_usage(response, provider): Logs token usage
- _local_complete(messages): Fallback to local model
Dependencies:
Internal: ai.gradient_client, ai.huggingface_client, config.config
External: tenacity, transformers (optional)
Execution Role: Abstracts LLM provider differences
Provider Chain: Gradient → HuggingFace → Local (distilgpt2)
Real Mode Behavior: Returns error, forces ADK agent usage
Test Mode: Returns deterministic JSON responses
Retry Strategy: 3 attempts, exponential backoff (1s-8s)
File: backend/src/ai/gradient_client.py
Purpose: DigitalOcean Gradient AI API client
Key Classes:
- GradientClient
Methods:
- chat(messages, stream): Chat completion request
- health(): Provider health check
Dependencies:
Internal: config.config
External: httpx
API Endpoint: {GRADIENT_BASE_URL}/chat/completions
Authentication: Bearer token (GRADIENT_API_KEY)
Timeout: 60 seconds
Models Supported: gpt-4.1-mini, llama3-70b, llama3-8b
File: backend/src/ai/huggingface_client.py
Purpose: HuggingFace Inference API client
Key Classes:
- HuggingFaceClient
Methods:
- complete(prompt): Text generation request
- health(): Provider health check
Dependencies:
Internal: config.config
External: httpx
API Endpoint: https://api-inference.huggingface.co/models/{model}
Authentication: Bearer token (HUGGINGFACE_API_KEY)
Timeout: 90 seconds
Default Model: HuggingFaceH4/zephyr-7b-beta
────────────────────────────────────────────────────────────────────────────
DIGITALOCEAN PROVIDER INTEGRATION
────────────────────────────────────────────────────────────────────────────
File: backend/src/providers/digitalocean/digitalocean_agent_router.py
Purpose: Routes requests to deployed ADK agents
Key Classes:
- DigitalOceanAgentRouter
Methods:
- route_to_agent(agent_name, prompt, context, trace_id, session_id, stream)
- route_to_agent_stream(agent_name, prompt, context, trace_id, session_id)
- health_check_all(): Checks all agent endpoints
Agent Mapping:
- planning: AXON_PLANNER_AGENT_URL
- research: AXON_RESEARCH_AGENT_URL
- reasoning: AXON_REASONING_AGENT_URL
- builder: AXON_BUILDER_AGENT_URL
Dependencies:
Internal: config.config, providers.digitalocean.digitalocean_agent_client,
providers.digitalocean.digitalocean_agent_types
Execution Role: Agent discovery and request routing
Headers: X-Trace-ID, X-AXON-SESSION
Streaming: Supports SSE-style streaming responses
File: backend/src/providers/digitalocean/digitalocean_agent_client.py
Purpose: HTTP client for ADK agent communication
Key Classes:
- DigitalOceanAgentClient
Methods:
- call_agent(agent_url, request, trace_id, session_id, stream)
- call_agent_stream(agent_url, request, trace_id, session_id)
- health_check(agent_url)
- _get_headers(trace_id, session_id): Builds request headers
- _retry_call(func, *args, **kwargs): Retry with exponential backoff
Dependencies:
Internal: config.config, providers.digitalocean.digitalocean_agent_types
External: httpx, tenacity
Timeout: Configurable via AXON_AGENT_TIMEOUT (default 120s)
Retry Strategy: 3 attempts, exponential backoff (1s-10s)
Authentication: Bearer token (DIGITALOCEAN_API_TOKEN)
Logging: Latency, payload sizes, trace/session IDs
File: backend/src/providers/digitalocean/digitalocean_agent_types.py
Purpose: Type definitions for agent communication
Key Classes:
- AgentRequest: Input schema (prompt, context)
- AgentResponse: Output schema (response, metadata, trace_id)
Dependencies:
External: pydantic
────────────────────────────────────────────────────────────────────────────
MEMORY AND VECTOR STORE
────────────────────────────────────────────────────────────────────────────
File: backend/src/memory/vector_store.py
Purpose: ChromaDB vector database operations
Key Classes:
- VectorStore
Methods:
- add_embedding(content, memory_type, task_id, metadata): Stores vector
- similarity_search(query, limit, task_id): Semantic search
- retrieve_context(task_prompt, task_id, limit): Context retrieval
Dependencies:
Internal: config.config, memory.embeddings
External: chromadb, asyncio
Storage: Persistent client at VECTOR_DB_PATH (./.chroma)
Fallback: EphemeralClient if persistent state corrupted
Collection: "axon_memory"
Metadata Fields: memory_type, task_id, custom metadata
Distance Metric: Default ChromaDB (L2)
File: backend/src/memory/embeddings.py
Purpose: Text embedding generation
Functions:
- embed(text): Generates embedding vector
- _load_model(): Loads sentence transformer (cached)
- _fallback_embedding(text, dim): Deterministic hash-based fallback
Dependencies:
Internal: config.config
External: sentence_transformers, hashlib
Model: sentence-transformers/all-MiniLM-L6-v2 (384 dimensions)
Fallback: SHA256-based deterministic vectors if model unavailable
Normalization: Embeddings are normalized
────────────────────────────────────────────────────────────────────────────
SKILLS SYSTEM
────────────────────────────────────────────────────────────────────────────
File: backend/src/skills/registry.py
Purpose: Skill discovery, registration, and management
Key Classes:
- SkillRegistry
- SkillDefinition (dataclass)
Methods:
- discover_skills(): Scans core_skills and generated_skills packages
- register_dynamic_skill(module_name): Loads skill from module path
- register_definition(definition): Registers skill definition
- all(): Returns all registered skills
- get(name): Retrieves skill by name
- generated_skills_path(): Returns path to generated_skills directory
- _iter_modules(package_name): Discovers modules in package
- _build_definition(module): Extracts skill metadata
Dependencies:
Internal: None
External: importlib, pkgutil, inspect, pathlib
Skill Metadata: name, description, parameters, version, execute function
Discovery Packages: src.skills.core_skills, src.skills.generated_skills
Skill Format: SKILL dict + execute() function
File: backend/src/skills/executor.py
Purpose: Executes registered skills with validation
Key Classes:
- SkillExecutor
Methods:
- execute(name, payload): Validates and executes skill
- _validate(expected, payload): Validates required parameters
Dependencies:
Internal: skills.registry
External: inspect
Execution: Supports both sync and async skill functions
Validation: Checks required parameters before execution
Output Format: {"skill": name, "version": version, "output": result}
File: backend/src/skills/core_skills/planning.py
Purpose: Task decomposition skill
Metadata:
name: planning
description: Break a task into executable steps
parameters: task (required), max_steps (optional)
version: 1.0.0
Algorithm: Returns predefined step templates (max 5 steps)
Output: {"task": str, "steps": [{"step": int, "description": str}]}
File: backend/src/skills/core_skills/coding.py
Purpose: Implementation scaffolding generation
Metadata:
name: coding
description: Generate implementation scaffolding
parameters: task (required), plan (optional)
version: 1.0.0
Output: {"summary": str, "artifacts": [{"type": str, "name": str}]}
File: backend/src/skills/core_skills/reasoning.py
Purpose: Strategy evaluation skill
Metadata:
name: reasoning
description: Evaluate options and tradeoffs
parameters: plan (required), context (optional)
version: 1.0.0
Algorithm: Calculates confidence score based on plan complexity
Output: {"confidence": float, "risks": [str], "recommendation": str}
File: backend/src/skills/generated_skills/web_search.py
Purpose: Web search placeholder skill
Metadata:
name: web_search
description: Synthesize search intent into research notes
parameters: query (required)
version: 1.0.0
Note: Placeholder implementation, no live web access
Output: {"query": str, "notes": [str]}
────────────────────────────────────────────────────────────────────────────
DATABASE LAYER
────────────────────────────────────────────────────────────────────────────
File: backend/src/db/models.py
Purpose: SQLAlchemy ORM models
Key Classes:
- Base: Declarative base
- TimestampMixin: id, created_at, updated_at fields
- Task: Task entity
- Skill: Skill entity
- AgentExecution: Agent execution record
- Artifact: File artifact metadata
- MemoryRecord: Memory/embedding reference
Dependencies:
External: sqlalchemy
ID Strategy: UUID4 strings (36 chars)
Timestamps: Timezone-aware, auto-managed
Relationships: Cascade deletes configured
File: backend/src/db/session.py
Purpose: Database session management
Functions:
- init_db(): Creates all tables
- close_db(): Disposes engine
- get_db_session(): Async session generator (FastAPI dependency)
Dependencies:
Internal: config.config, db.models
External: sqlalchemy.ext.asyncio
Connection Pool: 10 base, 20 overflow, 30s timeout (PostgreSQL)
Session Config: No autoflush, no expire on commit
Transaction: Auto-commit on success, rollback on exception
────────────────────────────────────────────────────────────────────────────
API LAYER
────────────────────────────────────────────────────────────────────────────
File: backend/src/api/routes/tasks.py
Purpose: Task management endpoints
Endpoints:
- GET /tasks/: List all tasks
- GET /tasks/{task_id}: Get task by ID
- POST /tasks/: Create new task
Dependencies: require_api_key, rate_limit_hook
Response Models: TaskListResponse, TaskResponse
Status Codes: 200 (GET), 201 (POST), 404 (not found)
File: backend/src/api/routes/skills.py
Purpose: Skill listing endpoints
Endpoints:
- GET /skills/: List all registered skills
Dependencies: require_api_key, rate_limit_hook
Response Models: SkillListResponse
File: backend/src/api/routes/evolution.py
Purpose: Evolution engine endpoints
Endpoints:
- GET /evolution/: Get evolution status
- POST /evolution/run: Trigger evolution
Dependencies: require_api_key, rate_limit_hook
Response Models: EvolutionStatus
File: backend/src/api/routes/system.py
Purpose: System health and status endpoints
Endpoints:
- GET /system/: System status check
Dependencies: require_api_key, rate_limit_hook
Response Models: SystemStatusResponse
Health Checks: Database, vector store, skills, agents, event bus, task queue
File: backend/src/api/websocket/event_stream.py
Purpose: Real-time event streaming via WebSocket
Endpoint: /ws/events
Protocol: WebSocket
Events: All EventBus events streamed to connected clients
Connection: Auto-subscribes on connect, unsubscribes on disconnect
Initial Message: {"event": "connected", "message": "..."}
File: backend/src/api/middleware/logging_middleware.py
Purpose: HTTP request logging middleware
Logs: method, path, status_code, duration_ms
Format: Structured JSON via Loguru
────────────────────────────────────────────────────────────────────────────
CONFIGURATION AND DEPENDENCIES
────────────────────────────────────────────────────────────────────────────
File: backend/src/config/config.py
Purpose: Application settings and environment variables
Key Classes:
- Settings (Pydantic BaseSettings)
Functions:
- get_settings(): Cached settings singleton
Configuration Fields:
- app_name: Application name (default: "AXON")
- env: Environment (default: "development")
- test_mode: Enable test mode (default: True)
- api_key: API authentication key
- gradient_api_key: DigitalOcean Gradient API key
- gradient_model: Model name (default: "gpt-4.1-mini")
- gradient_base_url: Gradient API endpoint
- huggingface_api_key: HuggingFace API key
- huggingface_model: HF model name
- database_url: PostgreSQL connection string
- embedding_model: Sentence transformer model
- vector_db_path: ChromaDB storage path
- cors_origins: CORS allowed origins
- request_rate_limit_per_minute: Rate limit (default: 120)
- axon_mode: Operating mode (mock/real)
- digitalocean_api_token: DO API token
- gradient_model_access_key: Gradient model access key
- digitalocean_kb_uuid: Knowledge base UUID
- axon_agent_timeout: Agent request timeout (default: 120s)
- axon_planner_agent_url: Planner agent URL
- axon_research_agent_url: Research agent URL
- axon_reasoning_agent_url: Reasoning agent URL
- axon_builder_agent_url: Builder agent URL
Dependencies:
External: pydantic-settings, python-dotenv
Loading: Reads from .env file via python-dotenv
File: backend/src/config/dependencies.py
Purpose: FastAPI dependency injection and singleton management
Singletons:
- _event_bus: EventBus instance
- _skill_registry: SkillRegistry instance
- _skill_executor: SkillExecutor instance
- _vector_store: VectorStore instance
- _llm_service: LLMService instance
- _orchestrator: AgentOrchestrator instance
- _task_manager: TaskManager instance
- _evolution_engine: EvolutionEngine instance
- _rate_state: Rate limiting state dict
Dependency Functions:
- get_app_settings(): Returns Settings
- get_event_bus(): Returns EventBus
- get_skill_registry(): Returns SkillRegistry
- get_llm_service(): Returns LLMService
- get_vector_store(): Returns VectorStore
- get_task_manager(): Returns TaskManager
- get_orchestrator(): Returns AgentOrchestrator
- get_evolution_engine(): Returns EvolutionEngine
- get_task_service(session): Returns TaskService
- get_skill_service(session): Returns SkillService
- get_evolution_service(session): Returns EvolutionService
- require_api_key(x_api_key, app_settings): API key validation
- rate_limit_hook(request, app_settings): Rate limiting
Rate Limiting: Per-IP, sliding window (60s), configurable limit
API Key: Optional, validates X-API-Key header
================================================================================
4. AGENT SYSTEM ANALYSIS
================================================================================
────────────────────────────────────────────────────────────────────────────
STANDALONE ADK AGENTS (agents/ directory)
────────────────────────────────────────────────────────────────────────────
PLANNER AGENT
Location: agents/planner_agent/main.py
Purpose: Task decomposition and planning
Framework: LangGraph + Gradient SDK
Model: openai-gpt-oss-120b (configurable)
Inference Endpoint: https://inference.do-ai.run
State Schema:
- prompt: str (task description)
- context: dict (additional context)
- plan: dict (generated plan)
Workflow Nodes:
- analyze_task: Main planning node
* Constructs system prompt for planning
* Calls Gradient chat completion
* Parses JSON response or wraps raw text
* Updates state with plan
Graph Structure:
Entry → analyze_task → END
Input Schema:
{
"prompt": "Task description",
"context": {"task_id": "...", ...}
}
Output Schema:
{
"response": "{\"steps\": [...]}", # JSON string
"metadata": {
"agent": "planner",
"version": "1.0.0"
}
}
Dependencies:
- gradient-adk: Agent deployment framework
- gradient: Gradient SDK for inference
- langgraph: State machine framework
Environment Variables:
- GRADIENT_MODEL_ACCESS_KEY: Model access key (required)
- GRADIENT_MODEL: Model name (default: openai-gpt-oss-120b)
- DIGITALOCEAN_API_TOKEN: DO API token
- DIGITALOCEAN_KB_UUID: Knowledge base UUID
Deployment:
Command: gradient-adk deploy
Entrypoint: @entrypoint decorator on main()
Runtime: DigitalOcean serverless infrastructure
RESEARCH AGENT
Location: agents/research_agent/main.py
Purpose: Information gathering and research
Framework: LangGraph + Gradient SDK
Model: openai-gpt-oss-120b (configurable)
Inference Endpoint: https://inference.do-ai.run
State Schema:
- prompt: str (research query)
- context: dict (additional context)
- research: dict (research results)
Workflow Nodes:
- conduct_research: Main research node
* Retrieves documents from Knowledge Base (if configured)
* Augments prompt with KB context
* Calls Gradient chat completion
* Structures research output
Graph Structure:
Entry → conduct_research → END
Knowledge Base Integration:
- Uses client.retrieve.documents() for semantic search
- Retrieves top 5 documents matching query
- Appends document content to prompt context
- Gracefully handles KB unavailability
Input Schema:
{
"prompt": "Research topic",
"context": {"task_id": "...", "plan": {...}}
}
Output Schema:
{
"response": "{\"notes\": \"...\", \"sources\": \"...\"}",
"metadata": {
"agent": "research",
"version": "1.0.0"
}
}
Special Features:
- Knowledge Base retrieval (optional)
- Document context augmentation
- Fallback to pure LLM if KB unavailable
Dependencies: Same as Planner Agent
Environment Variables: Same as Planner Agent + DIGITALOCEAN_KB_UUID
REASONING AGENT
Location: agents/reasoning_agent/main.py
Purpose: Strategy evaluation and logical analysis
Framework: LangGraph + Gradient SDK
Model: openai-gpt-oss-120b (configurable)
Inference Endpoint: https://inference.do-ai.run
State Schema:
- prompt: str (evaluation request)
- context: dict (plan and context)
- reasoning: dict (analysis results)
Workflow Nodes:
- evaluate_strategy: Main reasoning node
* Constructs evaluation prompt
* Calls Gradient chat completion with lower temperature (0.3)
* Structures reasoning output with confidence score
Graph Structure:
Entry → evaluate_strategy → END
Input Schema:
{
"prompt": "Strategy to evaluate",
"context": {"task_id": "...", "plan": {...}}
}
Output Schema:
{
"response": "{\"analysis\": \"...\", \"rationale\": \"...\"}",
"metadata": {
"agent": "reasoning",
"version": "1.0.0"
}
}
Temperature: 0.3 (lower for more deterministic reasoning)
Dependencies: Same as Planner Agent
Environment Variables: Same as Planner Agent
BUILDER AGENT
Location: agents/builder_agent/main.py
Purpose: Solution generation and implementation
Framework: LangGraph + Gradient SDK
Model: openai-gpt-oss-120b (configurable)
Inference Endpoint: https://inference.do-ai.run
State Schema:
- prompt: str (build request)
- context: dict (plan, reasoning, etc.)
- build: dict (solution output)
Workflow Nodes:
- generate_solution: Main building node
* Constructs solution prompt with all context
* Calls Gradient chat completion
* Structures build output
Graph Structure:
Entry → generate_solution → END
Input Schema:
{
"prompt": "Solution requirements",
"context": {"task_id": "...", "plan": {...}, "reasoning": {...}}
}
Output Schema:
{
"response": "{\"solution\": \"...\", \"implementation\": \"...\"}",
"metadata": {
"agent": "builder",
"version": "1.0.0"
}
}
Temperature: 0.7 (balanced creativity and consistency)
Dependencies: Same as Planner Agent
Environment Variables: Same as Planner Agent
────────────────────────────────────────────────────────────────────────────
AGENT DEPLOYMENT WORKFLOW
────────────────────────────────────────────────────────────────────────────
Prerequisites:
1. DigitalOcean account with Gradient AI access
2. gradient-adk CLI installed (pip install gradient-adk)
3. API token with agent deployment permissions
4. Model access key for Gradient inference
Deployment Steps (per agent):
1. Navigate to agent directory (e.g., agents/planner_agent)
2. Copy .env.example to .env
3. Configure environment variables:
- GRADIENT_MODEL_ACCESS_KEY
- GRADIENT_MODEL (optional, defaults to openai-gpt-oss-120b)
- DIGITALOCEAN_API_TOKEN
- DIGITALOCEAN_KB_UUID (optional, for research agent)
4. Run: gradient-adk deploy
5. Note the deployed agent URL (https://agents.do-ai.run/<agent-id>)
6. Update backend .env with agent URLs:
- AXON_PLANNER_AGENT_URL
- AXON_RESEARCH_AGENT_URL
- AXON_REASONING_AGENT_URL
- AXON_BUILDER_AGENT_URL
Local Testing:
Command: gradient-adk run --input '{"prompt": "test", "context": {}}'
Purpose: Test agent locally before deployment
Monitoring:
- View logs: gradient-adk logs <agent-id>
- Check status: gradient-adk status <agent-id>
- Health check: GET https://agents.do-ai.run/<agent-id>/health
Agent Endpoints:
- POST /run: Execute agent with input
- GET /health: Health check endpoint
Request Format:
{
"prompt": "User prompt",
"context": {"key": "value"},
"stream": false
}
Response Format:
{
"response": "Agent response (JSON string)",
"metadata": {"agent": "name", "version": "1.0.0"}
}
================================================================================
5. RUNTIME EXECUTION FLOW
================================================================================
────────────────────────────────────────────────────────────────────────────
COMPLETE REQUEST FLOW (REAL MODE)
────────────────────────────────────────────────────────────────────────────
1. USER REQUEST
Client → POST /tasks/
Payload: {"title": "Build API", "description": "Create REST endpoints"}
Headers: X-API-Key (if configured)
2. API LAYER
├─ LoggingMiddleware: Logs request start time
├─ require_api_key: Validates API key
├─ rate_limit_hook: Checks rate limit (per-IP, 60s window)
└─ TaskController.create_task()