Skip to content

Latest commit

 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ReAct Agent: Autonomous AI with Gemma 4 and Model Context Protocol (MCP)

A production-grade autonomous agent system implementing the ReAct (Reasoning + Acting) pattern with native tool execution, Model Context Protocol (MCP) server integration, hierarchical planning, self-critique, and working memory.


Architecture Overview

The system decomposes complex user tasks into concrete steps, executes tools across local and remote environments, and reflects on outcomes through an iterative loop.

User Task -> Planner -> ReAct Execution Loop -> Tool Action -> Observation -> Reasoning -> Final Output
                             |
                   +---------+---------+
                   |                   |
            Native Tools          MCP Servers
         (shell, python, etc.) (stdio, SSE, HTTP POST)

For complete architectural details, see DOCS/ARCHITECTURE.md.


Key Features

  • ReAct Reasoning Engine: Iterative thought, action selection, and observation handling.
  • Gemma 4 Model Integration: Optimized for Ollama-hosted Gemma 4 models with structured JSON parsing.
  • Model Context Protocol (MCP) Support: Full support for local Stdio servers, remote SSE servers, and Stateless/Streamable HTTP endpoints (such as Smithery.ai gateways).
  • Hierarchical Task Decomposition: Dynamic planning with dependency management and automated replanning upon tool failure.
  • Self-Critique & Reflection: Automated evaluation of tool output errors and recovery strategy selection.
  • Multi-Layer Memory: Short-term working message history and long-term episode recording.

Prerequisites

  • Operating System: Linux or macOS
  • Python: Version 3.10 or higher
  • Ollama: Installed and serving gemma4:12b locally

Step-by-Step Installation and Setup

Step 1: Install Ollama and Download Gemma 4

Install Ollama:

curl -fsSL https://ollama.com/install.sh | sh

Start the Ollama daemon:

ollama serve

Download the Gemma 4 12B model:

ollama pull gemma4:12b

Step 2: Set Up Python Environment

Navigate to the project root directory:

cd react_agent

Create and activate a virtual environment:

python3 -m venv venv
source venv/bin/activate

Install dependencies:

pip install -r requirements.txt

Step 3: Run System Verification

Run the diagnostic script to verify Ollama connectivity and tool registry setup:

python test_gemma4.py

Run unit tests:

PYTHONPATH=src python -m pytest tests/

Model Context Protocol (MCP) Setup

The agent supports local process servers (stdio) and remote HTTP/SSE servers, including Smithery.ai gateway endpoints.

1. Connecting to Smithery.ai Gateway Endpoint

Create a configuration JSON file (e.g. mcp_smithery_gateway.json):

[
  {
    "name": "smithery-gateway",
    "url": "https://mcp.smithery.run/YOUR_USERNAME",
    "transport": "sse",
    "api_key": "YOUR_SMITHERY_API_KEY"
  }
]

Run the agent with the MCP configuration:

python main.py --model gemma4:12b --mcp mcp_smithery_gateway.json

The agent automatically detects Stateless HTTP mode if an endpoint returns HTTP 405 on GET /sse requests, and falls back to HTTP POST JSON-RPC transport cleanly.

2. Local Stdio MCP Server Example

mcp_filesystem.json:

[
  {
    "name": "filesystem",
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user/documents"],
    "transport": "stdio"
  }
]

For full details on authentication, env vars, and transport specifications, refer to DOCS/MCP_INTEGRATION_GUIDE.md and MCP_SETUP.md.


Usage

Interactive REPL Mode

python main.py --model gemma4:12b

REPL Commands:

  • /tools: List all loaded native and MCP tools
  • /state: View current agent memory and state
  • /plan: Inspect active execution plan
  • /reset: Clear agent memory
  • exit: Quit the application

Non-Interactive Task Mode

python main.py --model gemma4:12b --task "Calculate 15 multiplied by 23 using python tool"

Python Library Usage

from react_agent import ReActAgent, AgentConfig

config = AgentConfig(llm_model="gemma4:12b")
agent = ReActAgent(config)

result = agent.run("Calculate 15 multiplied by 23 using python tool")
print(result)

agent.close()

For complete CLI options and Python API reference, see DOCS/USAGE_AND_CLI.md.

Web UI — Agent Studio (React + Vite)

The bundled web UI (web_ui/) is a streaming agent studio that visualizes the ReAct loop live: plan timelines, animated tool-call cards, thought traces with self-critique, markdown final answers, MCP gateway hub, chat history, light/dark themes, voice input, and a ⌘K command palette.

Run it (one-click, recommended):

./setup_agent.sh            # optional: pass a model, e.g. ./setup_agent.sh gemma4:12b

This script installs Ollama if missing, starts ollama serve, pulls the model (gemma4:12b by default, override with GEMMA_MODEL or the first argument), installs Python deps, builds web_ui/dist if empty, starts server.py, waits until /api/health responds, and opens the browser at http://localhost:8000.

Run it manually:

# 1. Build the frontend once
cd web_ui && npm install && npm run build && cd ..

# 2. Start the API bridge (serves web_ui/dist at http://localhost:8000)
python server.py

Run it (development, hot reload):

# Terminal 1 — API bridge
python server.py

# Terminal 2 — Vite dev server (proxies /api → localhost:8000)
cd web_ui && npm run dev   # → http://localhost:3000

New API endpoints added for the UI: GET /api/health, GET /api/models (Ollama model list, best-effort). The /api/run SSE stream now sends id: fields so reconnecting clients can resume with Last-Event-ID.

UI features for testing:

  • Stream a task: watch the plan board, live tool cards (running → success/error with durations), thinking dots, and streaming thought trace.
  • Try slash commands in the composer (/tools, /state, /plan, /reset, /help).
  • Connect an MCP gateway from the Plug button (presets + SSE/HTTP/stdio transports).
  • Use Ctrl/⌘+K for the command palette, the theme toggle for light/dark, and the history rail to reload past sessions (persisted in localStorage).

Documentation Directory Index

Detailed documentation files are available in the DOCS/ directory:


Configuration Settings

Settings can be customized via config/default.yaml or environment variables:

Variable Config Key Default Description
REACT_AGENT_MODEL llm_model gemma4:latest Ollama model identifier
REACT_AGENT_OLLAMA_URL ollama_base_url http://localhost:11434 Ollama server API base URL
REACT_AGENT_TEMPERATURE temperature 0.3 LLM generation temperature
REACT_AGENT_MAX_STEPS max_steps 25 Maximum ReAct loop steps
REACT_AGENT_LOG_LEVEL log_level INFO Logging verbosity level

Security Guidelines

  • Private credential files (such as mcp_smithery_gateway.json) containing API keys or bearer tokens must be added to .gitignore.
  • Use template files (mcp_smithery_gateway_template.json) when committing code to public version control.
  • Avoid passing sensitive tokens in plaintext CLI arguments when possible; prefer environment variables.

Project Structure

react_agent/
├── main.py                     # CLI entry point
├── test_gemma4.py              # Diagnostic test script
├── setup.py                    # Package setup script
├── requirements.txt            # Python dependencies
├── .gitignore                  # Git ignore patterns
├── README.md                   # Main documentation
├── MCP_SETUP.md                # Legacy MCP setup reference
├── config/
│   └── default.yaml            # Default agent configuration
├── DOCS/                       # Comprehensive documentation
│   ├── ARCHITECTURE.md         # System architecture specification
│   ├── INSTALLATION_AND_SETUP.md # Detailed setup instructions
│   ├── MCP_INTEGRATION_GUIDE.md# Complete MCP integration guide
│   └── USAGE_AND_CLI.md        # CLI commands and API guide
├── mcp_*.json                  # Config templates and examples
├── src/react_agent/            # Core library source code
│   ├── agent.py                # Main ReAct agent orchestrator
│   ├── llm.py                  # Ollama client interface
│   ├── models.py               # Pydantic data schemas
│   ├── config.py               # Config loader
│   ├── utils.py                # Logging and retries
│   ├── tools/                  # Native tool implementations and registry
│   ├── memory/                 # Working and episodic memory
│   ├── planning/               # Task planner and executor
│   ├── reasoning/              # ReAct reasoning engine
│   ├── mcp/                    # MCP transports, client, and adapter
│   └── prompts/                # Prompt templates
└── tests/                      # Pytest unit tests

License

MIT License

About

Autonomous ReAct AI Agent powered by Gemma 4 with native tools, hierarchical planning, and universal Model Context Protocol (MCP) support.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages