MangoAgent

from mango import MangoAgent          # or: from mango.agent import MangoAgent

Constructor

MangoAgent(
    llm_service: LLMService,
    tool_registry: ToolRegistry,
    db: NoSQLRunner,
    agent_memory: MemoryService | None = None,
    schema: dict[str, SchemaInfo] | None = None,
    introspect: bool = False,
    max_iterations: int = 8,
    max_retries: int = 2,
    memory_top_k: int = 3,
    training_top_k: int = 3,
    max_turns: int = 5,
    schema_top_k: int = 3,
    schema_always_all: int = 4,
    enable_text_memory: bool = True,
    text_memory_top_k: int = 2,
    text_memory_similarity_threshold: float = 0.55,
    text_memory_max_chars_per_note: int = 500,
    text_memory_max_total_chars: int = 1200,
    text_memory_include_unverified: bool = True,
    auto_save_memory: bool = True,
    middlewares: list[Middleware] | None = None,
)
ParameterDescription
llm_serviceLLM backend
tool_registryRegistered tools
dbConnected NoSQLRunner (schema introspection, db name)
agent_memoryVector memory; None disables memory features
schemaPre-computed schema; skips introspection
introspectRun introspect_schema() in setup(). Enables per-query schema injection, value hints and schema-linking enforcement
max_iterationsLLM ↔ tool round trips per question before a forced final answer
max_retriesCorrective retries after a fixable tool error
memory_top_k / training_top_kPast interactions / training examples injected per question
max_turnsConversation turns kept in history (older turns pruned whole)
schema_top_kCollections whose schema is injected per question (keyword relevance)
schema_always_allDatabases with at most this many collections get the full schema every time
enable_text_memory … text_memory_include_unverifiedRetrieval of free-text domain notes (top-k, similarity floor, character budgets, whether LLM-written notes are eligible)
auto_save_memoryPersist the last successful run_mql of each turn as a memory example
middlewaresAccess-control middlewares, see Access Control

Methods

setup() → None

Runs schema introspection if introspect=True, builds the value index and the system prompt. Called automatically on the first ask() if you do not call it.


ask(question, on_tool_call=None, *, user=None) → AgentResponse

async

  • question: str
  • on_tool_call: Callable[[str, dict, str], None] | None — called after each tool with (tool_name, tool_args, result_text)
  • user: Any — opaque caller object handed to the middlewares; never inspected by Mango

Raises AccessDenied when a before_turn middleware blocks the turn.

response = await agent.ask("How many users signed up last week?", user=current_user)

ask_stream(question, *, user=None) → AsyncGenerator[dict, None]

async generator — same as ask() but yields events as they happen:

typeFields
tool_calltool_name, tool_args
tool_resulttool_name, success, preview
answertext
doneiterations, input_tokens, output_tokens, memory_hits, tool_calls_made, retries_made

new_session() → MangoAgent

New agent, same configuration, fresh conversation. Schema, system prompt, value index and middleware chain are shared — creating a session is cheap, and use() on the root applies to every session.


reset_conversation() → None

Clears the history in place.


use(middleware) → Middleware

Registers an access-control middleware (runs in registration order).

agent.use(CollectionAccess(lambda u: ROLE_COLLECTIONS[u.role]))

Hook decorators

@agent.before_turn, @agent.filter_tools, @agent.before_tool, @agent.before_query, @agent.after_query, @agent.after_tool, @agent.before_answer, @agent.after_turn — register a plain function as a single-hook middleware.

@agent.before_query
def rule(ctx, query):
    ...
    return query

check_tool_access(user, tool_name, args=None) → None

Runs the before_tool hooks for user outside a turn; raises AccessDenied. Used by the HTTP layer to gate the memory endpoints (memory_train, memory_import, memory_export) and available to gate your own actions with the same rules.


Properties

PropertyTypeDescription
llm_serviceLLMServiceThe configured LLM
tool_registryToolRegistryThe tool registry
dbNoSQLRunnerThe connected database
agent_memoryMemoryService | NoneThe memory service
conversation_lengthintMessages in the current conversation

AgentResponse

@dataclass
class AgentResponse:
    answer: str                  # natural language answer
    tool_calls_made: list[str]   # names of tools called, in order
    input_tokens: int            # total input tokens across all LLM calls
    output_tokens: int           # total output tokens across all LLM calls
    iterations: int              # number of LLM calls in this turn
    memory_hits: int             # memory examples / notes injected
    retries_made: int            # corrective retries after tool errors

Exceptions

from mango.core.types import MangoError, ValidationError, QueryError, BackendError, AccessDenied
ExceptionRaised when
ValidationErrora query violates the read-only policy or is malformed
QueryErrorMongoDB rejected the query (retryable by the LLM)
BackendErrorconnection or infrastructure failure (not retryable)
AccessDeniedan access-control middleware blocked a call