An open API service indexing awesome lists of open source software.

https://github.com/persteenolsen/fastapi-jwt-auth-ai-agent-two

Python FastAPI with JWT Auth serving a Tool-Calling AI Agent running at Render
https://github.com/persteenolsen/fastapi-jwt-auth-ai-agent-two

ai-agent fastapi jwt python render

Last synced: 9 days ago
JSON representation

Python FastAPI with JWT Auth serving a Tool-Calling AI Agent running at Render

Awesome Lists containing this project

README

          

# ๐Ÿš€ FastAPI with JWT Auth serving a Tool-Calling AI Agent

A production-style AI Agent API built with FastAPI, featuring JWT authentication and a fully dynamic tool-calling architecture powered by Groq LLMs.

This project demonstrates a stable and extensible AI assistant built on a Tool Registry Agent Pattern, where tools are automatically exposed to the LLM, executed safely, and used to generate grounded responses.

# Version

At Render I use the PYTHON_VERSION environment variable to tell Render to use Python version 3.11. Locally I am using Python 3.12

---

## ๐Ÿ“Œ Project Info

- Version: 0.1.0
- Python: 3.11 / 3.12
- Architecture: Dynamic Tool Registry Agent (plan โ†’ execute โ†’ synthesize)
- Last Updated: 09-06-2026

---

## โœจ Key Features

### ๐Ÿ” Authentication
- JWT-based authentication (HS256)
- Protected `/chat` endpoint
- Token-based access control
- Environment-based credentials

---

### ๐Ÿค– AI Agent (Dynamic Tool System)
- LLM-driven tool selection from a dynamic registry
- No hardcoded tool list in prompts
- Tools auto-injected from `TOOL_REGISTRY`
- Execution pipeline: Plan โ†’ Execute โ†’ Synthesize
- Safe fallback to direct LLM response
- Protection against unknown tool execution

---

### ๐Ÿง  LLM Integration (Groq)
- Model: llama-3.3-70b-versatile
- High-speed inference via Groq API
- Temperature set to 0 for deterministic output
- Used for tool routing, query rewriting, and final synthesis

---

### ๐Ÿงฉ Tool Registry System
- Central `TOOL_REGISTRY` defines all tools
- LLM automatically receives tool list from registry
- Adding tools requires only creating the tool file and registering it
- Built-in tools:
- Wikipedia ๐Ÿ“š (general knowledge)
- Wikidata ๐Ÿงพ (structured facts)
- Calculator โž— (safe arithmetic engine)

---

### โž— Calculator Tool
- AST-based safe evaluator (no eval)
- Supports: +, -, *, /, %, **, // and parentheses
- Fully sandboxed execution
- Auto-used for pure math expressions

---

### ๐ŸŒ Wikipedia Tool
- Two-step retrieval:
- Search API for entity lookup
- REST summary API for content extraction
- Retry-enabled HTTP session
- Robust fallback handling

---

### ๐Ÿงพ Wikidata Tool
- Entity search via Wikidata API
- LLM-assisted query simplification
- Optimized for structured facts and rankings

---

## ๐Ÿ“ก API Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | /login | ๐Ÿ” Get JWT access token |
| POST | /chat | ๐Ÿ’ฌ Chat with AI agent |
| GET | /health | โค๏ธ Service health check |
| GET | /health/tools | ๐Ÿงฉ All registered tools health |
| GET | /health/tools/{tool_name} | ๐Ÿ” Single tool health check |

---

## โš™๏ธ Getting Started

### 1. Clone Repository
git clone https://github.com/your-username/your-repo.git
cd your-repo

### 2. ๐Ÿ Create Virtual Environment
python -m venv venv

Activate:

๐ŸชŸ Windows
venv\Scripts\activate

๐Ÿง Mac/Linux
source venv/bin/activate

### 3. ๐Ÿ“ฆ Install Dependencies
pip install -r requirements.txt

---

## ๐Ÿ”‘ Environment Variables

Create a `.env` file:

SECRET_KEY=your_secret_key_here
GROQ_API_KEY=your_groq_api_key
FAKE_USERNAME=admin
FAKE_PASSWORD=password

Generate secret key:

python -c "import secrets; print(secrets.token_hex(32))"

---

## โ–ถ๏ธ Run Application

uvicorn main:app --reload

๐ŸŒ API: http://127.0.0.1:8000
๐Ÿ“˜ Docs: http://127.0.0.1:8000/docs

---

## ๐Ÿ” Authentication Flow

1. Call `/login` with credentials
2. Receive JWT token
3. Send token in header: `Authorization: Bearer `
4. Access `/chat` endpoint

---

## ๐Ÿง  How the Agent Works

User message โ†’ LLM reads available tools from registry โ†’ LLM generates tool plan โ†’ Registry validates tools โ†’ Tools execute safely โ†’ Results collected โ†’ LLM generates final grounded response

---

## ๐Ÿ—๏ธ Architecture

### ๐ŸŸข Tool Registry Agent (Current System)

- Fully dynamic tool discovery
- No hardcoded tool list in prompt
- Safe execution via registry
- Extensible plug-and-play tools
- Deterministic execution pipeline

### ๐Ÿ”ต Not ReAct

This system does not use ReAct.
It does not:
- iterate reasoning step-by-step
- call tools in loops
- update reasoning after each tool call

Instead:

Plan โ†’ Execute โ†’ Synthesize

---

## ๐Ÿ’ฌ Example Requests

### No tool example

POST /chat
{
"message": "Tell me a joke"
}

{
"response": "What do you call a fake noodle? An impasta.",
"tools_used": [],
"steps": [
"tool_plan=[]"
],
"error_id": null
}

---

### Calculator Example

POST /chat
{
"message": "What is 25 * 18 + 10?"
}

{
"response": "To calculate the result of the expression \"25 * 18 + 10\", we can follow the order of operations. First, we multiply 25 by 18, which equals 450. Then, we add 10 to this result, giving us a final answer of 460. This calculation is confirmed by the provided tool data from the calculator, which also yields a result of 460 for the expression \"25 * 18 + 10\". Therefore, the answer to the given expression is 460.",
"tools_used": [
{
"tool": "calculator",
"query": "25 * 18 + 10",
"success": true
}
],
"steps": [
"tool_plan=[{'name': 'calculator', 'query': '25 * 18 + 10'}]"
],
"error_id": null
}

---

### Wikipedia Example

POST /chat
{
"message": "What is AI?"
}

{
"response": "According to the provided Wikipedia data, Artificial Intelligence (AI) refers to the ability of computational systems to perform tasks that are typically associated with human intelligence. These tasks include learning, reasoning, problem-solving, perception, and decision-making. In essence, AI is a field of research that focuses on developing methods and software to enable machines to perceive their environment, learn, and take actions to achieve specific goals.",
"tools_used": [
{
"tool": "wikipedia",
"query": "Artificial intelligence",
"success": true
}
],
"steps": [
"tool_plan=[{'name': 'wikipedia', 'query': 'Artificial intelligence'}]"
],
"error_id": null
}

---

## ๐Ÿš€ Benefits

- ๐Ÿงฉ Fully extensible tool system
- ๐Ÿง  No prompt maintenance required when adding tools
- ๐Ÿ›ก๏ธ Safe execution layer for all tools
- ๐Ÿงฑ Clean separation of agent / tools / API
- โš™๏ธ Production-ready FastAPI structure
- ๐Ÿ“Š Deterministic and debuggable behavior

---

## ๐Ÿšง Current Limitations

- Stateless per request
- Single-step planning only
- No streaming responses yet
- Limited tool ecosystem

---

## ๐Ÿš€ Future Improvements

- ๐Ÿง  Conversation memory
- ๐ŸŒŠ Streaming responses (SSE/WebSockets)
- โšก Parallel tool execution
- ๐Ÿ“Š Tool confidence scoring
- ๐Ÿ’พ Caching layer for Wikipedia/Wikidata
- ๐Ÿ”— Multi-step tool chaining

---

## ๐Ÿ“„ License

MIT License

---

## ๐Ÿ™Œ Final Notes

This project implements a modern dynamic tool registry architecture where tools are first-class citizens and the LLM dynamically adapts to available capabilities, enabling a scalable foundation for multi-tool AI systems.