Package reference
stacgis-ai (Python import name stacgis_ai) is a production-ready
harness for building AI agents: a ReAct loop, MCP tooling, LLM provider
abstractions, conversation memory, human-in-the-loop approvals and drop-in
FastAPI routers.
Package layout
stacgis_ai/
├── __init__.py # public API surface (see below)
├── _version.py # __version__
├── exceptions.py # exception hierarchy (StacGisAIError base class)
├── frontend_tools.py # @frontend_tool — server tools that emit UI events
├── agent/ # ReAct engine
│ ├── loop.py # AgentLoop — think → act → observe → respond
│ ├── mcp_client.py # MCPClient — in-memory (FastMCP) or HTTP transport
│ ├── approval_registry.py# ApprovalRegistry — human-in-the-loop decisions
│ └── config.py # AgentConfig (exported as AgentLoopConfig)
├── core/ # orchestration primitives
│ ├── orchestrator.py # AgentOrchestrator
│ ├── tool_registry.py # ToolRegistry, Tool
│ ├── circuit_breaker.py # CircuitBreaker (CLOSED/OPEN/HALF_OPEN)
│ ├── retry_policy.py # RetryPolicy, RetryStrategy
│ └── types.py # Pydantic models (requests, results, states)
├── decorators/ # @ai_tool, @agent, @workflow
├── fastapi_integration/ # routers, WebSocket, OpenAPI generation
│ ├── routers.py # create_flow_router / create_agent_router / …
│ ├── websocket.py # create_websocket_endpoint
│ └── openapi_generator.py# generate_tool_routes
├── llm/ # LLMProvider, OllamaProvider (+ streaming merger,
│ # OpenAI-compatible, text tool-call parsing)
├── memory/ # ConversationMemory — context-window management
└── observability/ # hooks, metrics, structured logging
Public API (from stacgis_ai)
Agent
| Name | Description |
|---|---|
AgentLoop | ReAct agent loop — run() (blocking) and streaming variants; parallel tool execution, cancellation, step budgets |
AgentLoopConfig | Loop configuration (max_steps, system_prompt, …) |
AgentState | Loop states: thinking → acting → observing → responding |
AgentStep | One streamed step (state, message, tool call/result, timing) |
AgentRunResult | Final result of a run (response, steps, …) |
MCPClient | Connect to a FastMCP server (in-memory) or an HTTP MCP endpoint; exposes tool schemas; approval_tools={...} gates tools behind HitL approval |
MCPClientConfig | MCP client configuration (transport, URL, timeout) |
ToolSchema | LLM-facing tool description (name, description, JSON schema) |
ApprovalRegistry / ApprovalRequest / ApprovalDecision | Human-in-the-loop: pause the loop, await approve/reject (with timeout) |
DEFAULT_SYSTEM_PROMPT | Default ReAct system prompt |
Core orchestration
| Name | Description |
|---|---|
AgentOrchestrator | Coordinates tool execution with retries, circuit breaking and hooks |
ToolRegistry | Register/lookup/search tools, batch execution |
Tool | A registered callable with metadata, retry & circuit-breaker settings |
CircuitBreaker | CLOSED → OPEN → HALF_OPEN failure isolation |
RetryPolicy / RetryStrategy | Backoff/retry configuration |
ToolDefinition, ToolExecutionRequest, ToolExecutionResult | Pydantic request/result models |
BatchExecutionRequest / BatchExecutionResult | Parallel tool batch execution |
CircuitState | Circuit breaker state enum |
Decorators
| Name | Description |
|---|---|
@ai_tool | Turn a plain (async) function into a registered tool with LLM schema; supports approval, retry, circuit-breaker options |
@agent | Mark a class/function as an agent entry point with configuration |
@workflow | Mark a function as a multi-step workflow |
FastAPI integration
| Name | Description |
|---|---|
create_flow_router(prefix="/stacgis_ai") | Main router: /health, /tools/schema, /tools/{name}, /execute, /execute/batch |
create_agent_router(get_loop, prefix="/agent") | Agent router: POST /agent/chat, POST /agent/stream (SSE), POST /agent/approval/{id} |
create_tools_router(...) | Tools-only router |
create_websocket_endpoint(...) | WebSocket streaming endpoint |
generate_tool_routes(...) | One REST route per registered tool (OpenAPI-friendly) |
get_orchestrator / get_tool_registry | FastAPI dependency providers |
OrchestratorProvider | Provider object tying loop + registry together |
ApprovalDecisionRequest | Pydantic model for the approval endpoint |
LLM providers
| Name | Description |
|---|---|
LLMProvider | Abstract provider interface (chat + streaming) |
OllamaProvider / OllamaConfig | Ollama: native streaming, text-based tool-call fallback |
LLMResponse, ToolCall, StreamChunk | Provider-agnostic response models |
extract_tool_calls_from_text | Parse tool calls from plain-text LLM output |
validate_tool_call | Validate a tool call against its schema |
Memory
| Name | Description |
|---|---|
ConversationMemory | Context-window management + trimming for long conversations |
Observability
| Name | Description |
|---|---|
AgentHooks | Event hooks (before/after tool calls, step transitions, …) |
HookManager / get_hook_manager | Register & dispatch hooks |
MetricsCollector / get_metrics / set_metrics / disable_metrics | Runtime metrics (Prometheus-compatible when installed) |
AgentLogger / LogContext | Structured, JSON-friendly logging |
Frontend tools
| Name | Description |
|---|---|
@frontend_tool | Server-side tool that emits a UI event (zoom_to, draw_geometry, show_toast, …) to the React client instead of returning a value |
FrontendToolRegistry / FrontendToolDefinition | Registration & schema for frontend tools |
Exceptions
All derive from StacGisAIError:
ToolNotFoundError, ToolRegistrationError, ToolExecutionError,
ApprovalRequiredError, CircuitOpenError, ValidationError,
WorkflowError, DependencyError, RateLimitExceededError,
LLMProviderError, EmbeddingError, ContextLengthExceededError,
MemoryError, AgentLoopError, MCPConnectionError.
Environment variables
| Variable | Used by | Meaning |
|---|---|---|
OLLAMA_BASE_URL | OllamaProvider | Ollama server URL (default http://localhost:11434) |
OLLAMA_MODEL | example apps | Model name to request |