MASAI
A Python framework for agents that use tools, retain context, and work together. MASAI calls the native Gemini, Anthropic, and OpenAI SDKs. The core agent workflow does not require LangChain.
This guide describes version 0.6.7. Read it in order, then use the linked chapters for details.
Contents
- Feature map
- 1. Install
- 2. Configure models
- 3. Run the first agent
- 4. Use tools and planning
- 5. Add context callbacks
- 6. Cache prompt prefixes
- 7. Keep memory and sessions
- 8. Stream results
- 9. Coordinate agents
- 10. Understand the architecture
- 11. Upgrade and troubleshoot
- 12. Reference and development
- 13. License
Feature map
| Area | Features | Guide |
|---|---|---|
| Agent workflow | Router, evaluator, reflector, optional planner, typed tools, direct return, parallel tool calls, and runtime tool discovery | Tools and planning |
| Agent controls | Memory windows, summaries, tool/reflection limits, deadlines, output limits, per-component overrides, and model-specific settings | Model config |
| Providers | Gemini, Anthropic, and OpenAI wrappers; native request fields; structured output; client options; model rejection overrides | Provider settings |
| Prompt context | Context callbacks, constant/dynamic fields, base INFO, history, summaries, tool output, and peer context | Context callbacks |
| Caching | Provider prompt-prefix caching and separate synchronous Redis tool-result caching | Prompt caching, tool cache |
| Conversation state | Component histories, summaries, retained task state, dump/restore, request identity, and caller isolation | Agent state, sessions |
| Data and memory | Documents, embeddings, in-memory store, Qdrant and Redis vector memory, metadata filters, and deduplication | Memory, documents, embeddings |
| Multiple agents | Sequential runs, decentralized delegation, streaming handoffs, hierarchical supervisor, task queue, and result callbacks | Multi-agent workflows |
| Streaming | Graph state updates, provider chunks, structured response events, and server-sent events | Streaming |
| Framework internals | Manager, graph, prompts, model factory, wrappers, memory adapters, tools, and extension points | Architecture, API reference |
| Other modules | OMAN and migration notes for older guide content | API reference, older-guide coverage |
1. Install
Use Python 3.11 for the checked release setup. Install version 0.6.7 or later:
python -m pip install "masai-framework>=0.6.7"
A local wheel or source checkout works before publication.
Create your application in its own folder and name the script app.py.
See installation.
| Provider | Key variable | Alternative |
|---|---|---|
| Gemini | GOOGLE_API_KEY |
GEMINI_API_KEY |
| Anthropic | ANTHROPIC_API_KEY |
CLAUDE_API_KEY |
| OpenAI | OPENAI_API_KEY |
Set the key for the provider you use.
load_dotenv() reads an application's .env file.
2. Configure models
Save model_config.json beside app.py.
The all block is the fallback for agents without a named block.
Each block defines a router, evaluator, reflector, and optional planner.
{
"all": {
"router": {"model_name": "gemini-3.8-flash", "category": "gemini", "max_output_tokens": 4096},
"evaluator": {"model_name": "gemini-3.8-flash", "category": "gemini", "max_output_tokens": 4096},
"reflector": {"model_name": "gemini-3.8-flash", "category": "gemini", "max_output_tokens": 4096},
"planner": {"model_name": "gemini-3.8-flash", "category": "gemini", "max_output_tokens": 4096}
}
}
A named agent block replaces the fallback block; it is not a partial merge. Use lowercase names and provide all components needed by that agent. The full sample config also shows Anthropic and OpenAI.
MASAI uses its own settings internally and forwards native provider parameters.
Flat native fields and provider_params both work.
client_options configures SDK clients, such as their timeout.
The SDK and selected model decide which native fields are valid.
Read model config and provider parameters.
3. Run the first agent
Save this complete script as app.py:
import asyncio
from pathlib import Path
from dotenv import load_dotenv
from masai.AgentManager import AgentDetails, AgentManager
from masai.Tools.Tool import tool
load_dotenv()
@tool("add", return_direct=True)
def add(a: int, b: int) -> int:
"""Add two integers."""
return a + b
async def main():
manager = AgentManager(
model_config_path=str(Path(__file__).with_name("model_config.json")),
logging=False,
)
agent = manager.create_agent(
agent_name="assistant",
tools=[add],
agent_details=AgentDetails(
capabilities=["arithmetic"],
description="Use add for addition.",
style="concise",
),
long_context=False,
max_total_tool_calls=5,
run_timeout_seconds=60,
)
result = await agent.initiate_agent("Use add to calculate 2 + 2.", passed_from="user")
print(result["answer"])
if __name__ == "__main__":
asyncio.run(main())
python app.py
The router selects add and its inputs.
MASAI validates those inputs, runs the function, and returns its direct result.
Read the quick-start walkthrough.
4. Use tools and planning
Tool and @tool turn typed functions into tools.
return_direct=True lets a tool finish a task.
Other tools pass their results to an evaluator.
Set execute_multiple_tools=True for independent calls in one turn.
Set plan=True to add a planner; the config then needs a planner component.
The planner replaces the router as the graph entry when enabled.
Tool discovery and runtime tool updates rebuild the answer schema.
| Control | Default | Effect |
|---|---|---|
plan |
False |
Add a planner and use it as the graph entry |
execute_multiple_tools |
False |
Run independent tool calls together |
max_total_tool_calls |
25000 | Hard per-run tool cap; 0 disables it |
max_tool_loop |
3 | Warn on repeated identical calls; advisory only |
max_reflection_count |
3 | Bound reflection attempts |
max_recursion_limit |
100 | Graph recursion ceiling |
run_timeout_seconds |
0 | Deadline between graph steps; 0 disables it |
max_tool_output_words |
3000 | Bound tool text included in prompts |
tool_output_similarity_threshold |
0 | Truncate exact repeats only; positive values enable fuzzy matching |
Other controls include memory_order, long_context, shared_memory_order, retain_messages_order, context_callable, callable_config, tool_registry, long_context_model, and character_factor.
See all agent and model controls.
Choose a suitable tool cap for your application.
A graph deadline does not interrupt an SDK call already in flight.
Use a client timeout too.
See tools and planning.
5. Add context callbacks
Callbacks fetch context before a model call. A plain dictionary is fully dynamic. Use this return type to choose reusable fields:
from masai.GenerativeModel import ContextResult
def context_for_turn(text: str):
return ContextResult(
constant={"workflow_guide": "Use add for arithmetic."},
dynamic={"current_task": text},
)
Pass it as context_callable for user-input calls.
Use callable_config for later nodes that need fresh context.
The input starts with the current question and adds prior node reasoning when available.
Callback results are local to the call.
See context callbacks.
Read agent state for base context and conversation lifetime,
and request context for caller identity in tools.
6. Cache prompt prefixes
The default prompt order is:
System + component instructions
Response/tool schema and peers
Callback constant context <-- one cache boundary
Agent name, time, dynamic INFO, history, long context, question
The caller chooses constant fields; MASAI does not guess them.
The wrappers apply each provider's native cache settings.
There is no common caching=true switch.
| Provider | Component setting |
|---|---|
| Anthropic | "cache_control": {"type": "ephemeral", "ttl": "5m"} |
| OpenAI, on supported models | "prompt_cache_options": {"mode": "explicit", "ttl": "30m"} |
| Gemini | Native implicit caching; no enable flag |
A cache marker makes a prefix eligible; it does not guarantee a hit. A changed word inside that prefix can require a new write. The name and live context stay after the prefix. The callback still runs and the request still contains fresh dynamic data. Read MASAI prompt caching for setup, provider behavior, usage checks, and limits. For synchronous data lookups, tool-result caching is a separate Redis feature.
7. Keep memory and sessions
Component history, summaries, persistent memory, and provider caching have separate roles.
Agent summaries are enabled by default and can add model calls.
The first example disables them with long_context=False.
dump_session() exports runtime state; load_session() restores it after agent creation.
Clients, credentials, tools, and graphs are not serialized.
Persistent memory supports Qdrant and Redis with a supplied embedding model.
See memory and sessions.
Use Documents for text, metadata, and serialization.
Use embedding adapters to connect native APIs or local models.
8. Stream results
initiate_agent_astream() yields graph updates.
Provider token chunks are a separate interface.
A structured Anthropic response is yielded once it is complete.
EnhancedStreamHandler converts agent events to server-sent events.
It cancels active stream work when the consumer disconnects.
See streaming.
9. Coordinate agents
Create all agents in one manager, then create MultiAgentSystem.
Sequential runs pass results in order.
Decentralized runs let agents delegate to peers.
Hierarchical runs use a supervisor and task manager.
Use separate agent/session state for separate callers. See multi-agent workflows.
10. Understand the architecture
AgentManager chooses config and builds the components. The provider registry builds each wrapper and client. During a run, the agent graph calls MASGenerativeModel to render context and send requests. The model returns a validated decision; MASAI executes local tools.
The framework owns its state and request structure. Native provider fields remain available to the selected SDK. Read architecture and data flow, including the detailed agent graph and multi-agent flows.
11. Upgrade and troubleshoot
Version 0.6.7 fixes Anthropic structured output for recent models and supports Python 3.13+. Version 0.6.6 changed native parameter forwarding, callback lifetime, and cache placement. See migration and troubleshooting. The older-guide coverage table maps retained topics and corrects obsolete examples.
12. Reference and development
The documentation book links all chapters in reading order. Use the API reference for exact entry points.
From a source checkout:
python -m pip install -e ".[dev]"
python -m pytest
python -m ruff check src tests
python -m ruff format --check src tests
python -m build
python -m twine check dist/*
Default tests stay offline. See contributing and the changelog.
13. License
Metadata
Release files for masai-framework 0.6.7
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| masai_framework-0.6.7.tar.gz | 1.9 MB | Without provenance | Details for masai_framework-0.6.7.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| masai_framework-0.6.7-py3-none-any.whl | Python 3 | none | any | Details for masai_framework-0.6.7-py3-none-any.whl |
Total release size: 2.1 MB
Release files / masai_framework-0.6.7.tar.gz
| Download URL | masai_framework-0.6.7.tar.gz |
|---|---|
| Size | 1.9 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a20bd40a2054b9e3437b8456ce617f7b9a99e9a263c7a30d8d74dee77eec2065
|
|
BLAKE2b-256 checksum How to use checksums |
da9082d0157a223ef01e0823770f2b4c04723932896c5444a2fef170a5aab375
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.9
|
Release files / masai_framework-0.6.7-py3-none-any.whl
| Download URL | masai_framework-0.6.7-py3-none-any.whl |
|---|---|
| Size | 187.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
012231d20fed10d24061513da492637d600f557bee500d044a5ad4add5a2655d
|
|
BLAKE2b-256 checksum How to use checksums |
148d0e5a644174b18607623df9893d105210cd0fe7672e588f7325a6e2c326c8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.9
|
Security for masai-framework 0.6.7
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.