Skip to main content

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

NameDescription
AgentLoopReAct agent loop — run() (blocking) and streaming variants; parallel tool execution, cancellation, step budgets
AgentLoopConfigLoop configuration (max_steps, system_prompt, …)
AgentStateLoop states: thinking → acting → observing → responding
AgentStepOne streamed step (state, message, tool call/result, timing)
AgentRunResultFinal result of a run (response, steps, …)
MCPClientConnect to a FastMCP server (in-memory) or an HTTP MCP endpoint; exposes tool schemas; approval_tools={...} gates tools behind HitL approval
MCPClientConfigMCP client configuration (transport, URL, timeout)
ToolSchemaLLM-facing tool description (name, description, JSON schema)
ApprovalRegistry / ApprovalRequest / ApprovalDecisionHuman-in-the-loop: pause the loop, await approve/reject (with timeout)
DEFAULT_SYSTEM_PROMPTDefault ReAct system prompt

Core orchestration

NameDescription
AgentOrchestratorCoordinates tool execution with retries, circuit breaking and hooks
ToolRegistryRegister/lookup/search tools, batch execution
ToolA registered callable with metadata, retry & circuit-breaker settings
CircuitBreakerCLOSED → OPEN → HALF_OPEN failure isolation
RetryPolicy / RetryStrategyBackoff/retry configuration
ToolDefinition, ToolExecutionRequest, ToolExecutionResultPydantic request/result models
BatchExecutionRequest / BatchExecutionResultParallel tool batch execution
CircuitStateCircuit breaker state enum

Decorators

NameDescription
@ai_toolTurn a plain (async) function into a registered tool with LLM schema; supports approval, retry, circuit-breaker options
@agentMark a class/function as an agent entry point with configuration
@workflowMark a function as a multi-step workflow

FastAPI integration

NameDescription
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_registryFastAPI dependency providers
OrchestratorProviderProvider object tying loop + registry together
ApprovalDecisionRequestPydantic model for the approval endpoint

LLM providers

NameDescription
LLMProviderAbstract provider interface (chat + streaming)
OllamaProvider / OllamaConfigOllama: native streaming, text-based tool-call fallback
LLMResponse, ToolCall, StreamChunkProvider-agnostic response models
extract_tool_calls_from_textParse tool calls from plain-text LLM output
validate_tool_callValidate a tool call against its schema

Memory

NameDescription
ConversationMemoryContext-window management + trimming for long conversations

Observability

NameDescription
AgentHooksEvent hooks (before/after tool calls, step transitions, …)
HookManager / get_hook_managerRegister & dispatch hooks
MetricsCollector / get_metrics / set_metrics / disable_metricsRuntime metrics (Prometheus-compatible when installed)
AgentLogger / LogContextStructured, JSON-friendly logging

Frontend tools

NameDescription
@frontend_toolServer-side tool that emits a UI event (zoom_to, draw_geometry, show_toast, …) to the React client instead of returning a value
FrontendToolRegistry / FrontendToolDefinitionRegistration & 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

VariableUsed byMeaning
OLLAMA_BASE_URLOllamaProviderOllama server URL (default http://localhost:11434)
OLLAMA_MODELexample appsModel name to request