Spaces:
Paused
Paused
File size: 8,100 Bytes
9f4dea0 | 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 | # AI Agents
Nexus uses [LangGraph](https://github.com/langchain-ai/langgraph) to orchestrate a master agent graph that handles all natural-language workspace queries. The graph is defined in `agents/nexus_master.py` and is invoked via `POST /api/v1/nexus/query/` and the streaming `POST /api/v1/nexus/stream/`.
---
## Master agent graph
```
User query
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β NexusMasterGraph β
β β
β [entry] βββΆ intent_router β
β β β
β ββββββββββββββΌβββββββββββββ¬ββββββββββββββ β
β βΌ βΌ βΌ βΌ β
β kb_search ticket_ops analytics remediation β
β β β β β β
β ββββββββββββββ΄βββββββββββββ΄ββββββββββββββ β
β β β
β response_synthesizer β
β β β
β [RBAC output masking] β
β β β
ββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββ
βΌ
Structured response
```
### Nodes
| Node | File | Description |
|---|---|---|
| `intent_router` | `agents/routing.py` | Classifies the query and selects which sub-nodes to invoke. Uses a small structured-output LLM call. |
| `kb_search` | `agents/kb_node.py` | Semantic + keyword search over KB articles. Returns ranked chunks with article metadata. |
| `ticket_ops` | `agents/nexus_master.py` | Create, update, or query tickets on behalf of the user via the `create_ticket` and `search_tickets` tools. |
| `analytics` | `agents/analytics.py` | Runs aggregation queries (SLA, sentiment, volume trends) and formats a narrative answer. |
| `remediation` | `agents/remediation.py` | Suggests resolution steps based on similar past tickets and KB articles. |
| `response_synthesizer` | `agents/nexus_master.py` | Merges outputs from all invoked nodes into a single coherent response. Appends source citations. |
### State
The graph carries a typed `NexusState` dict across nodes:
```python
class NexusState(TypedDict):
messages: list[BaseMessage]
workspace_id: str
user_role: str
intent: str | None
kb_results: list[KBResult]
ticket_results: list[TicketResult]
analytics_data: dict | None
final_answer: str | None
sources: list[Source]
tokens_used: int
```
### Persistence (checkpointing)
Every interaction is checkpointed to `NexusCheckpoint` rows in PostgreSQL via `agents/nexus_checkpoint.py`. This lets conversations resume across HTTP requests using the `thread_id`. LangGraph's `SqliteSaver` interface is adapted to use the async SQLAlchemy session.
---
## Tools
Tools are defined in `agents/tools/nexus_tools.py` and registered with the LangGraph `ToolNode`.
| Tool | Description |
|---|---|
| `search_kb` | Vector + keyword KB search with workspace scope |
| `search_tickets` | Hybrid search across workspace tickets |
| `create_ticket` | Create a ticket on behalf of the user (CUSTOMER_* roles only) |
| `get_ticket_details` | Fetch a single ticket's full thread |
| `get_workspace_analytics` | Pull aggregated metrics for a time window |
| `analyze_sentiment` | Score a block of text using the LLM |
| `suggest_resolution` | Match a problem description to past resolutions |
LangChain built-in tools (e.g. `DuckDuckGoSearchRun`) are available but disabled by default β see `agents/tools/langchain_tools.py`.
---
## LLM providers
The agent layer supports multiple providers configured via environment variables:
| Variable | Default | Role |
|---|---|---|
| `AI_PROVIDER` | `anthropic` | Primary text generation |
| `AI_TEXT_PROVIDER` | `anthropic` | Overrides text provider for agent nodes |
| `AI_TEXT_EMBEDDING_PROVIDER` | `ollama` | Embedding generation |
| `AI_MODEL` | `claude-3-haiku-20240307` | Model ID for primary provider |
Provider resolution is centralised in `core/llm.py`, which returns a `BaseChatModel` regardless of the backend. Supported backends: Anthropic Claude, Ollama, Google Gemini, Azure OpenAI.
Embeddings always go through Ollama (`nomic-embed-text`, 768 dimensions) by default. To use a cloud embedding API, set `AI_TEXT_EMBEDDING_PROVIDER=anthropic` or `openai`.
---
## RBAC output masking
`agents/security.py` intercepts the synthesized response before it is returned to the API. It applies role-based field stripping:
| Field | CUSTOMER_* | SC_AGENT | SC_LEAD+ |
|---|---|---|---|
| Internal notes | Hidden | Visible | Visible |
| Agent assignment details | Hidden | Visible | Visible |
| SLA breach reasons | Hidden | Hidden | Visible |
| Personnel analytics | Hidden | Hidden | Visible |
| Raw LLM reasoning trace | Hidden | Hidden | SUPERADMIN only |
The masking is additive β each role sees a strict subset of higher roles.
---
## Background AI jobs
The heavy ARQ worker runs several AI jobs that feed agent quality over time:
### `auto_summarize_ticket` (`tasks/ai.py`)
Triggered after a ticket is created or significantly updated. Generates two summaries using the primary LLM:
- **Customer summary** β plain-language, no internal context.
- **Internal summary** β full context including agent notes and SLA metadata.
Both are stored in `Ticket.ai_metadata` as structured JSON.
### `crystallize_memory` (`tasks/ai.py`)
When a `NexusThread` exceeds a message threshold, this job compresses the conversation history into a `NexusMemory` record using an LLM summarization prompt. Future interactions load the memory instead of the full history, keeping context windows bounded.
### `index_kb_article` (`tasks/ai.py`)
After a KB article is created or updated:
1. Split into overlapping chunks (configurable size/overlap).
2. Embed each chunk via Ollama.
3. Upsert vectors into the pgvector `kb_article_chunks` table.
4. Update the article's TSVECTOR column for full-text search.
### `generate_workspace_insights` (`tasks/analytics.py`)
Runs every 6 hours per workspace. Aggregates ticket metrics, feeds them into a prompt, and stores the resulting markdown narrative in `WorkspaceInsight` for the dashboard.
### `harvest_expertise_task` (`tasks/nexus_ai.py`)
After ticket resolution, extracts structured knowledge (problem pattern + resolution steps) and creates or updates a `KnowledgeInsight` linked to the relevant KB article.
---
## Prompts
All prompts live in `agents/prompts.py` as versioned string templates. Key prompts:
| Prompt | Purpose |
|---|---|
| `INTENT_CLASSIFICATION_PROMPT` | Map user message β intent label |
| `KB_SYNTHESIS_PROMPT` | Merge KB chunks into a coherent answer |
| `TICKET_SUMMARY_CUSTOMER_PROMPT` | Customer-facing ticket summary |
| `TICKET_SUMMARY_INTERNAL_PROMPT` | Internal ticket summary with full context |
| `WORKSPACE_INSIGHT_PROMPT` | Narrative insights from aggregated metrics |
| `MEMORY_CRYSTALLIZATION_PROMPT` | Compress long conversation history |
Prompts are injected with workspace context (name, active projects, role) to ground the LLM in the workspace's domain.
---
## Further reading
- [Agentic workflows deep-dive](backend_insights/10_agentic_workflows.md)
- [KB ingestion pipeline](backend_insights/07_kb_ingestion.md)
- [AI observability](backend_insights/06_ai_observability.md)
- [Multimodal pipeline](backend_insights/03_multimodal_pipeline.md)
|