Agent Observatory & Tool-Calling RAG Workflow Guide
This skill guides agents and engineers on how to build, extend, test, and enhance AI agent services utilizing Tool-Calling RAG, LangChain/LiteLLM architectures, and pgvector embeddings.
1. Local Branch-First Development
[!IMPORTANT]
CREATE A LOCAL BRANCH FIRST: Always start by creating a dedicated local branch from main:
git switch -c <developer-or-agent>/main/<feature-name>
Never develop or modify agent code directly on main.
2. Adding a New Agent Tool
- Create or update a tool file under your agent tools directory (e.g.
agent/tools/ or data/tools/):from typing import Annotated, Any
from langchain_core.tools import tool
@tool
async def inspect_custom_metric(
metric_name: Annotated[str, "The name of the metric to query"],
days: Annotated[int, "Number of lookback days"] = 7,
) -> dict[str, Any]:
"""Query operational metrics from the database or external API."""
# Perform database query or API call
return {"metric": metric_name, "value": 42}
- Export the tool in the tools package
__init__.py.
- Register the tool in your central agent runner's
TOOLS list.
3. Tool-Calling RAG & Vector Knowledge Base
The AI service operates as a Tool-Calling RAG Agent:
- Pre-turn Retrieval: Injects top relevance chunks into system context before iteration 1.
- Dynamic Tool Calling: The agent calls
hybrid_search_knowledge_base during reasoning loops for deep evidence gathering:from agent.tools import hybrid_search_knowledge_base
- Supported source filters:
['chat_message', 'execution_log', 'investigation', 'task_result', 'incident_fix'].
- Combines Full-Text Search (tsvector), pgvector cosine similarity, and Reciprocal Rank Fusion (RRF).
4. Implementing Human-In-The-Loop (HITL) Actions
For sensitive or destructive actions (e.g., dispatching external emails, modifying records, triggering external deployments):
- In the agent reasoning execution loop, intercept the tool call prior to execution:
if tool_name in SENSITIVE_ACTION_TOOLS:
confirm_id = str(uuid.uuid4())
confirm_event = asyncio.Event()
active_confirmations[confirm_id] = confirm_event
yield json.dumps({
"type": "confirm_required",
"confirm_id": confirm_id,
"name": tool_name,
"args": tool_args,
})
# Await user confirmation or timeout
await asyncio.wait_for(confirm_event.wait(), timeout=120.0)
- Feed the user approval or rejection payload back to the LLM context to continue execution safely.
5. Multi-Key API Failover
When interacting with external LLM APIs (e.g. OpenRouter, OpenAI, Anthropic):
- Maintain an in-memory pool of configured API keys.
- On HTTP
401, 402, or 429 (rate limit/quota exhaustion), rotate to the next backup key with exponential backoff and jitter.
- Track latency and failure counts per key to optimize routing.
6. Comprehensive Agent Test Suites
Execute verification test suites:
# 1. Run all unit and integration tests across the system
make test
# 2. Run dedicated AI Agent & Tool-Calling RAG test suite
make test-agents
# 3. Direct execution of agent evaluation tests
uv run python -m unittest discover -s tests -p "test_agent*.py"
1---2name: agent-observatory-workflow3description: Step-by-step instructions for building and extending Python AI agent services: adding LangChain/LiteLLM tools, Tool-Calling RAG workflows, enforcing Human-in-the-Loop approvals, multi-key model failover, and pgvector embeddings.4---56# Agent Observatory & Tool-Calling RAG Workflow Guide78This skill guides agents and engineers on how to build, extend, test, and enhance AI agent services utilizing Tool-Calling RAG, LangChain/LiteLLM architectures, and pgvector embeddings.910---1112## 1. Local Branch-First Development1314> [!IMPORTANT]15> **CREATE A LOCAL BRANCH FIRST**: Always start by creating a dedicated local branch from `main`:16> ```bash17> git switch -c <developer-or-agent>/main/<feature-name>18> ```19> Never develop or modify agent code directly on `main`.2021---2223## 2. Adding a New Agent Tool24251. Create or update a tool file under your agent tools directory (e.g. `agent/tools/` or `data/tools/`):26 ```python27 from typing import Annotated, Any28 from langchain_core.tools import tool2930 @tool31 async def inspect_custom_metric(32 metric_name: Annotated[str, "The name of the metric to query"],33 days: Annotated[int, "Number of lookback days"] = 7,34 ) -> dict[str, Any]:35 """Query operational metrics from the database or external API."""36 # Perform database query or API call37 return {"metric": metric_name, "value": 42}38 ```392. Export the tool in the tools package `__init__.py`.403. Register the tool in your central agent runner's `TOOLS` list.4142---4344## 3. Tool-Calling RAG & Vector Knowledge Base4546The AI service operates as a **Tool-Calling RAG Agent**:471. **Pre-turn Retrieval**: Injects top relevance chunks into system context before iteration 1.482. **Dynamic Tool Calling**: The agent calls `hybrid_search_knowledge_base` during reasoning loops for deep evidence gathering:49 ```python50 from agent.tools import hybrid_search_knowledge_base51 ```52 * Supported source filters: `['chat_message', 'execution_log', 'investigation', 'task_result', 'incident_fix']`.53 * Combines Full-Text Search (tsvector), pgvector cosine similarity, and Reciprocal Rank Fusion (RRF).5455---5657## 4. Implementing Human-In-The-Loop (HITL) Actions5859For sensitive or destructive actions (e.g., dispatching external emails, modifying records, triggering external deployments):601. In the agent reasoning execution loop, intercept the tool call prior to execution:61 ```python62 if tool_name in SENSITIVE_ACTION_TOOLS:63 confirm_id = str(uuid.uuid4())64 confirm_event = asyncio.Event()65 active_confirmations[confirm_id] = confirm_event6667 yield json.dumps({68 "type": "confirm_required",69 "confirm_id": confirm_id,70 "name": tool_name,71 "args": tool_args,72 })73 # Await user confirmation or timeout74 await asyncio.wait_for(confirm_event.wait(), timeout=120.0)75 ```762. Feed the user approval or rejection payload back to the LLM context to continue execution safely.7778---7980## 5. Multi-Key API Failover8182When interacting with external LLM APIs (e.g. OpenRouter, OpenAI, Anthropic):83- Maintain an in-memory pool of configured API keys.84- On HTTP `401`, `402`, or `429` (rate limit/quota exhaustion), rotate to the next backup key with exponential backoff and jitter.85- Track latency and failure counts per key to optimize routing.8687---8889## 6. Comprehensive Agent Test Suites9091Execute verification test suites:92```bash93# 1. Run all unit and integration tests across the system94make test9596# 2. Run dedicated AI Agent & Tool-Calling RAG test suite97make test-agents9899# 3. Direct execution of agent evaluation tests100uv run python -m unittest discover -s tests -p "test_agent*.py"101```