### FastAPI Agent - Installation Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Instructions on how to install the FastAPI Agent package using pip or uv. ```APIDOC ## Installation To install the package, run: ```bash # install with pip pip install fastapi_agent # install with uv uv add fastapi_agent ``` ``` -------------------------------- ### Discover and Execute FastAPI Routes Source: https://context7.com/orco82/fastapi-agent/llms.txt This section demonstrates how to iterate through discovered API routes, print their details, generate usage examples, and programmatically execute routes using the discovery object. It covers GET and POST requests with and without parameters. ```python import asyncio # Iterate through discovered routes for route in discovery.routes_info: print(f"\n{route.method} {route.path}") print(f" Name: {route.name}") print(f" Description: {route.description}") print(f" Parameters: {route.parameters}") print(f" Request Body: {route.request_body}") print(f" Response Model: {route.response_model}") print(f" Tags: {route.tags}") # Generate usage example example = discovery.get_route_usage_example(route) print(f" Usage: {example}") # Get allowed HTTP methods methods = discovery.get_allow_methods() print(f"\nAllowed methods: {methods}") # ['GET', 'POST'] # Execute routes programmatically async def execute_routes(): # Execute GET request result = await discovery.execute_route("GET", "/items") print(f"GET /items: {result}") # Output: {'status_code': 200, 'data': [...], 'headers': {...}} # Execute GET with parameters result = await discovery.execute_route( "GET", "/items/1", include_details=True ) print(f"GET /items/1: {result}") # Execute POST with data result = await discovery.execute_route( "POST", "/items", data={"name": "New Item", "price": 19.99, "description": "A new product"} ) print(f"POST /items: {result}") # Close the HTTP client when done await discovery.close() # asyncio.run(execute_routes()) ``` -------------------------------- ### Install FastAPI Agent Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Installs the fastapi-agent package using pip or uv. This is the initial step to integrate the agent into your FastAPI application. ```bash pip install fastapi_agent ``` ```bash uv add fastapi_agent ``` -------------------------------- ### Install Development Dependencies for FastAPI Agent Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Command to install the necessary development dependencies for the FastAPI Agent project, including testing and coverage tools. This is a prerequisite for running the test suite. ```bash # Install development dependencies pip install -e ".[dev]" ``` -------------------------------- ### Query API Endpoints via POST Request Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Example of how to query the FastAPI Agent's default '/agent/query' endpoint using a POST request. This allows natural language interaction to discover API functionality. ```bash curl -k -X POST "http://127.0.0.1:8000/agent/query" \ -H "Content-Type: application/json" \ -d '{"query": "show all endpoints"}' ``` -------------------------------- ### FastAPI Agent - Basic Usage Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Example of how to integrate FastAPI Agent into a FastAPI application. ```APIDOC ## Usage To use the FastAPI Agent, initialize it with your FastAPI app and AI model. Here is a simple example: #### .env ```bash OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` #### app.py ```python import uvicorn from dotenv import load_dotenv from fastapi import FastAPI from fastapi_agent import FastAPIAgent # load OPENAI_API_KEY from .env load_dotenv() # set your FastAPI app app = FastAPI( title="YOUR APP TITLE", version="0.1.0", description="SOME DESCRIPTION", ) # add routes @app.get("/") async def root(): """Welcome endpoint that returns basic API information""" return {"message": "Welcome to Test API"} # add the FastAPI Agent + default routes FastAPIAgent( app, model="openai:gpt-4.1-mini", base_url="http://localhost:8000", include_router=True, ) # run FastAPI uvicorn.run(app, host="0.0.0.0", port=8000) ``` ``` -------------------------------- ### Add Custom Tools to Agent Instance Source: https://github.com/orco82/fastapi-agent/blob/main/CLAUDE.md Extend the agent's capabilities by adding custom tools using the `add_custom_tool()` method. This allows the agent to utilize user-defined functions for specific tasks. Refer to `examples/pydantic_ai_tools.py` for examples. ```python agent = AIAgent.create(model="openai:gpt-4.1-mini") agent.add_custom_tool(my_custom_function) ``` -------------------------------- ### GET /agent/chat Source: https://github.com/orco82/fastapi-agent/blob/main/README.md A simple web-based chat interface to interact with your API. ```APIDOC ## GET /agent/chat ### Description A simple web-based chat interface to interact with your API. ### Method GET ### Endpoint /agent/chat ### Parameters None ### Request Example None ### Response #### Success Response (200) - **HTML** - The HTML content for the chat interface. #### Response Example (Returns an HTML page for the chat UI) ``` -------------------------------- ### Configure FastAPIAgent with Options (Python) Source: https://context7.com/orco82/fastapi-agent/llms.txt This Python code snippet shows how to initialize the FastAPIAgent with several configuration options. It includes setting the LLM model, base URL, authentication, route filtering, and additional behavioral flags like `verify_api_call`, `logo_url`, and `debug`. ```python from fastapi import FastAPI from fastapi_agent import FastAPIAgent app = FastAPI(title="Configured Agent") @app.get("/data") async def get_data(): """Get application data""" return {"data": "value"} @app.post("/data") async def create_data(payload: dict): """Create new data (modifying operation)""" return {"created": payload} @app.delete("/data/{id}") async def delete_data(id: int): """Delete data by ID (dangerous operation)""" return {"deleted": id} # Full configuration example agent = FastAPIAgent( app, model="openai:gpt-4.1-mini", base_url="http://localhost:8000", include_router=True, # Authentication (optional) auth={"Authorization": "Bearer secret-token"}, # Route filtering (optional) ignore_routes=["DELETE:/data/{id}"], # Additional options via kwargs verify_api_call=True, # Ask user confirmation before POST/PUT/DELETE (default: True) logo_url="https://example.com/my-logo.png", # Custom logo for chat UI debug=True, # Enable debug logging ) # When verify_api_call=True, the agent will ask: # "I'm about to create new data. Should I proceed with POST /data?" # When verify_api_call=False, the agent executes immediately without confirmation ``` -------------------------------- ### Basic FastAPI App with FastAPI Agent Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Demonstrates initializing a FastAPI application and integrating the FastAPI Agent. It loads the OpenAI API key from a .env file and adds default agent routes for querying and chatting with the API. ```python import uvicorn from dotenv import load_dotenv from fastapi import FastAPI from fastapi_agent import FastAPIAgent # load OPENAI_API_KEY from .env load_dotenv() # set your FastAPI app app = FastAPI( title="YOUR APP TITLE", version="0.1.0", description="SOME DESCRIPTION", ) # add routes @app.get("/") async def root(): """Welcome endpoint that returns basic API information""" return {"message": "Welcome to Test API"} # add the FastAPI Agent + default routes FastAPIAgent( app, model="openai:gpt-4.1-mini", base_url="http://localhost:8000", include_router=True, ) # run FastAPI uvicorn.run(app, host="0.0.0.0", port=8000) ``` -------------------------------- ### FastAPIAgent Initialization with Authentication Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Demonstrates how to initialize the FastAPI Agent, including passing API keys or Bearer tokens for authentication to your application's routes. ```APIDOC ## POST /agent/query (with Authorization Depends) ### Description This section explains how to pass authorization details when your application routes use Authorizations Depends (e.g., Headers or Query String API key or HTTP_Bearer). The agent uses these details to call your routes and also applies them to the `/agent/query` route. ### Method POST ### Endpoint /agent/query ### Parameters #### Query Parameters - **query** (string) - Required - The query to send to the agent. #### Request Body This endpoint does not have a request body, but requires specific headers for authentication. ### Headers - **auth** (string) - Required - A JSON string representing the authentication details. This can be in the format `{"api-key": "YOUR_API_KEY"}` or `{"Authorization": "Bearer YOUR_BEARER_TOKEN"}`. ### Request Example (Python) ```python import requests # Example with API Key res = requests.post( "http://127.0.0.1:8000/agent/query", json={"query": "show all endpoints"}, headers={"auth": '{"api-key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}'} ) print(res.json()) # Example with Bearer Token res = requests.post( "http://127.0.0.1:8000/agent/query", json={"query": "show all endpoints"}, headers={"auth": '{"Authorization": "Bearer 12345678"}'} ) print(res.json()) ``` ### Request Example (curl) ```bash # Example with API Key curl -k -X POST "http://127.0.0.1:8000/agent/query" \ -H 'auth: {"api-key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}' \ -H "Content-Type: application/json" \ -d '{"query": "show all endpoints"}' # Example with Bearer Token curl -k -X POST "http://127.0.0.1:8000/agent/query" \ -H 'auth: {"Authorization": "Bearer 12345678"}' \ -H "Content-Type: application/json" \ -d '{"query": "show all endpoints"}' ``` ### Response #### Success Response (200) - **response** (object) - The agent's response to the query. #### Response Example ```json { "response": "The agent processed your query and returned the relevant information." } ``` ``` -------------------------------- ### Development and Testing Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Provides instructions on how to set up the development environment, run tests, and understand test coverage for the FastAPI Agent. ```APIDOC ## Development & Testing ### Description Information on how to run tests and check test coverage for the FastAPI Agent project. ### Running Tests #### Install Development Dependencies ```bash pip install -e ".[dev]" ``` #### Run All Tests ```bash pytest ``` #### Run Tests with Coverage Report ```bash pytest --cov=fastapi_agent --cov-report=term-missing ``` #### Run Specific Test File ```bash pytest tests/test_auth.py ``` #### Generate HTML Coverage Report ```bash pytest --cov=fastapi_agent --cov-report=html ``` ### Test Coverage - **77 tests** covering authentication detection, route discovery, and agent orchestration. - **79% overall coverage** with critical components at 80%+ coverage. - All external dependencies (LLM calls, HTTP requests) are mocked for fast, reliable tests. ``` -------------------------------- ### Initialize FastAPIAgent with Default Routes Source: https://context7.com/orco82/fastapi-agent/llms.txt This snippet demonstrates how to initialize the FastAPIAgent within a FastAPI application. It automatically discovers routes, detects authentication, and includes default API endpoints for querying and chatting with the agent. Ensure you have your OpenAI API key set in your environment variables. ```python import uvicorn from dotenv import load_dotenv from fastapi import FastAPI from pydantic import BaseModel from typing import List, Optional from fastapi_agent import FastAPIAgent load_dotenv() # Load OPENAI_API_KEY from .env # Create your FastAPI application app = FastAPI( title="User Management API", version="1.0.0", description="A user management API with AI agent integration", ) # Define Pydantic models class User(BaseModel): name: str email: str age: Optional[int] = None class UserResponse(BaseModel): id: int name: str email: str age: Optional[int] = None # Mock database users_db = [ {"id": 1, "name": "Alice", "email": "alice@example.com", "age": 30}, {"id": 2, "name": "Bob", "email": "bob@example.com", "age": 25}, ] # Define your API routes @app.get("/users", response_model=List[UserResponse], tags=["users"]) async def list_users(): """Retrieve all users from the database""" return users_db @app.get("/users/{user_id}", response_model=UserResponse, tags=["users"]) async def get_user(user_id: int): """Get a specific user by their unique ID""" user = next((u for u in users_db if u["id"] == user_id), None) if not user: raise HTTPException(status_code=404, detail="User not found") return user @app.post("/users", response_model=UserResponse, tags=["users"]) async def create_user(user: User): """Create a new user in the system""" new_user = {"id": len(users_db) + 1, **user.model_dump()} users_db.append(new_user) return new_user # Initialize FastAPI Agent with default routes FastAPIAgent( app, model="openai:gpt-4.1-mini", # LLM model to use base_url="http://localhost:8000", # Base URL for API calls include_router=True, # Add /agent/query and /agent/chat routes ) # Run the application # Access chat UI at: http://localhost:8000/agent/chat # Query API at: POST http://localhost:8000/agent/query uvicorn.run(app, host="0.0.0.0", port=8000) ``` -------------------------------- ### Create AIAgent with Custom Tools Source: https://context7.com/orco82/fastapi-agent/llms.txt This snippet shows how to create an AI agent using the AIAgent factory, either directly or via a factory method. It demonstrates adding custom tools like 'get_weather', 'calculate', and 'search_database' using decorators and how to interact with the agent through chat. ```python import asyncio from pydantic_ai import RunContext from fastapi_agent.agents import AIAgent, PydanticAIAgent, DEFAULT_PROMPT # Option 1: Create agent using factory (recommended) agent = AIAgent.create( model="openai:gpt-4.1-mini", prompt=DEFAULT_PROMPT, # Optional custom prompt provider="pydantic_ai", # Currently only pydantic_ai is supported ) # Option 2: Create agent directly # agent = PydanticAIAgent( # model_name="openai:gpt-4.1-mini", # prompt="You are a helpful assistant with custom tools.", # ) # Add custom tools using the decorator pattern @agent.add_custom_tool async def get_weather(ctx: RunContext[None], location: str) -> dict: """ Get current weather information for a location. Args: location: The city or location to get weather for Returns: dict: Weather information including temperature, description, humidity """ # Mock weather data (replace with real API call) weather_data = { "New York": {"temp": 22.5, "desc": "Partly cloudy", "humidity": 65}, "London": {"temp": 15.0, "desc": "Rainy", "humidity": 80}, "Tokyo": {"temp": 28.0, "desc": "Sunny", "humidity": 55}, } data = weather_data.get(location, {"temp": 20.0, "desc": "Unknown", "humidity": 60}) return { "location": location, "temperature": data["temp"], "description": data["desc"], "humidity": data["humidity"], } @agent.add_custom_tool def calculate(ctx: RunContext[None], expression: str) -> float: """ Safely evaluate mathematical expressions. Args: expression: Mathematical expression to evaluate (e.g., "2 + 3 * 4") Returns: float: Result of the calculation """ allowed_chars = set("0123456789+-*/.() ") if not all(c in allowed_chars for c in expression): raise ValueError("Invalid characters in expression") return float(eval(expression)) @agent.add_custom_tool async def search_database(ctx: RunContext[None], query: str, limit: int = 10) -> list: """ Search the database for matching records. Args: query: Search query string limit: Maximum number of results to return Returns: list: Matching database records """ # Mock database search return [ {"id": 1, "title": f"Result for '{query}'", "score": 0.95}, {"id": 2, "title": f"Related to '{query}'", "score": 0.87}, ][:limit] # Chat with the agent (maintains conversation history) async def main(): history = [] questions = [ "What tools do you have available?", "What's the weather in Tokyo?", "Calculate 15 * 7 + 23", "Search the database for 'python tutorials'", ] for question in questions: print(f"\nUser: {question}") response, history = await agent.chat(question, history) print(f"Agent: {response}") asyncio.run(main()) ``` -------------------------------- ### FastAPIAgent Initialization with Route Control Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Illustrates how to configure the FastAPI Agent to either ignore specific routes or only allow access to a defined set of routes using `ignore_routes` or `allow_routes`. ```APIDOC ## FastAPIAgent Configuration (Route Control) ### Description Control which routes the agent can access using the `ignore_routes` or `allow_routes` arguments during FastAPI Agent initialization. ### Method N/A (Configuration during initialization) ### Endpoint N/A ### Parameters #### Initialization Arguments - **ignore_routes** (list of strings) - Optional - A list of routes to exclude from agent access. Format: `["METHOD:/path"]`. - **allow_routes** (list of strings) - Optional - A list of routes to restrict agent access to. Format: `["METHOD:/path"]`. ### Request Example (Python) ```python from fastapi import FastAPI from fastapi_agent.fastapi_agent import FastAPIAgent app = FastAPI() # Example using ignore_routes agent_ignore = FastAPIAgent( app, model="openai:gpt-4.1-mini", base_url="https://localhost:8000", ignore_routes=["DELETE:/users/{user_id}"], include_router=True, ) # Example using allow_routes agent_allow = FastAPIAgent( app, model="openai:gpt-4.1-mini", base_url="https://localhost:8000", allow_routes=["GET:/items", "POST:/items"], include_router=True, ) ``` ### Response N/A (Configuration during initialization) ``` -------------------------------- ### Configure FastAPI Agent with Authorizations Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Demonstrates how to initialize FastAPIAgent with authorization credentials for API key or Bearer token authentication. This ensures the agent can securely interact with protected routes. ```python api_key = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" FastAPIAgent( app, model="openai:gpt-4.1-mini", base_url="https://localhost:8000", auth={"api-key": API_KEY} || {'Authorization': "Bearer API_KEY"}, include_router=True, ) ``` -------------------------------- ### POST /agent/query Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Ask anything about your API using natural language. ```APIDOC ## POST /agent/query ### Description Ask anything about your API using natural language. ### Method POST ### Endpoint /agent/query ### Parameters #### Request Body - **query** (string) - Required - The natural language query about the API. ### Request Example ```json { "query": "show all endpoints" } ``` ### Response #### Success Response (200) - **response** (string) - The answer to the query about the API. #### Response Example ```json { "response": "The API has the following endpoints: / and /agent/query." } ``` ``` -------------------------------- ### Run FastAPI Agent Tests with Pytest Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Commands to execute the test suite for the FastAPI Agent using pytest. Includes options for running all tests, running with coverage reports (terminal and HTML), and running specific test files. ```bash # Run all tests pytest # Run with coverage report pytest --cov=fastapi_agent --cov-report=term-missing # Run specific test file pytest tests/test_auth.py # Generate HTML coverage report pytest --cov=fastapi_agent --cov-report=html ``` -------------------------------- ### Interact with FastAPI Agent Query API Source: https://context7.com/orco82/fastapi-agent/llms.txt Demonstrates how to query the FastAPI agent's `/agent/query` endpoint using cURL and Python requests. Supports sending queries, maintaining conversation history, and authenticating requests with API keys or Bearer tokens. The response includes the query, agent's response, status, and error information. ```bash # Query the agent via API curl -X POST "http://localhost:8000/agent/query" \ -H "Content-Type: application/json" \ -d '{"query": "What endpoints are available?"}' # Response format: # { # "query": "What endpoints are available?", # "response": "This API has the following endpoints...", # "status": "success", # "error": null, # "history": [...] # } # Query with conversation history curl -X POST "http://localhost:8000/agent/query" \ -H "Content-Type: application/json" \ -d '{ "query": "Tell me more about the first endpoint", "history": [ {"role": "user", "content": "What endpoints are available?"}, {"role": "assistant", "content": "This API has GET /users and POST /users..."} ] }' # Query with authentication (when auth is configured) curl -X POST "http://localhost:8000/agent/query" \ -H "Content-Type: application/json" \ -H 'auth: {"api-key": "your-api-key-here"}' \ -d '{"query": "Show me all protected endpoints"}' # Alternative auth header format for Bearer tokens curl -X POST "http://localhost:8000/agent/query" \ -H "Content-Type: application/json" \ -H 'auth: {"Authorization": "Bearer your-token-here"}' \ -d '{"query": "Access the secure data endpoint"}' # Access the web chat interface # Open in browser: http://localhost:8000/agent/chat ``` ```python # Python requests example import requests # Simple query response = requests.post( "http://localhost:8000/agent/query", json={"query": "List all users"} ) result = response.json() print(f"Response: {result['response']}") print(f"Status: {result['status']}") # Query with authentication response = requests.post( "http://localhost:8000/agent/query", json={"query": "Get user details for ID 1"}, headers={"auth": '{"api-key": "secret-key-12345"}'} ) print(response.json()) # Maintain conversation across requests history = [] for question in ["What can you do?", "Show me the users", "How do I create a new user?"]: response = requests.post( "http://localhost:8000/agent/query", json={"query": question, "history": history} ) result = response.json() print(f"Q: {question}") print(f"A: {result['response']}\n") history = result.get("history", []) ``` -------------------------------- ### Call Agent Query Endpoint with Authorizations (Python) Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Illustrates how to make a POST request to the `/agent/query` endpoint using Python's `requests` library, including passing authorization headers for API key or Bearer token authentication. This is used when your application routes have authorization dependencies. ```python import requests res = requests.post( "http://127.0.0.1:8000/agent/query", json={"query": "show all endpoints"}, headers={"auth": '{"api-key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}'} - OR - headers={"auth": '{"Authorization": "Bearer 12345678"}'} ) print(res.json()) ``` -------------------------------- ### Discover API Routes with FastAPIDiscovery Source: https://context7.com/orco82/fastapi-agent/llms.txt Utilize the `FastAPIDiscovery` class to inspect a FastAPI application's routes and metadata without adding AI functionality. This is useful for API introspection, documentation generation, or programmatic route execution. ```python from fastapi import FastAPI from pydantic import BaseModel from typing import Optional from fastapi_agent import FastAPIDiscovery app = FastAPI(title="Discovery Example") class Item(BaseModel): name: str price: float description: Optional[str] = None @app.get("/items") async def list_items(): """List all available items""" return [{"id": 1, "name": "Widget", "price": 9.99}] @app.post("/items", response_model=Item) async def create_item(item: Item): """Create a new item""" return item @app.get("/items/{item_id}") async def get_item(item_id: int, include_details: bool = False): """Get item by ID with optional details""" return {"id": item_id, "name": "Widget", "price": 9.99} # Initialize discovery discovery = FastAPIDiscovery( app, base_url="http://localhost:8000", ) # Get OpenAPI spec (without paths) openapi_spec = discovery.get_openapi_spec() print(f"API Title: {openapi_spec['info']['title']}") print(f"API Version: {openapi_spec['info']['version']}") # Get human-readable routes summary routes_summary = discovery.get_routes_summary() print("\n--- Routes Summary ---") print(routes_summary) ``` -------------------------------- ### Call Agent Query Endpoint with Authorizations (curl) Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Demonstrates how to call the `/agent/query` endpoint using `curl`, including passing authorization headers for API key or Bearer token authentication. This is relevant when your application routes have authorization dependencies. ```bash curl -k -X POST "http://127.0.0.1:8000/agent/query" \ -H 'auth: {"api-key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}' \ - OR - -H 'auth: {"Authorization": "Bearer 12345678"}' \ -H "Content-Type: application/json" \ -d '{"query": "show all endpoints"}' ``` -------------------------------- ### Configure FastAPI Agent Authentication Source: https://github.com/orco82/fastapi-agent/blob/main/CLAUDE.md Configure authentication credentials for the FastAPI Agent when routes use dependency injection. The agent automatically detects the authentication type (header-based or Bearer tokens) and injects the credentials into requests. ```python FastAPIAgent( app, auth={"api-key": "xxx"} # For header-based auth # OR auth={"Authorization": "Bearer xxx"} # For Bearer tokens ) ``` -------------------------------- ### POST /agent/query Source: https://context7.com/orco82/fastapi-agent/llms.txt This endpoint allows you to query the agent programmatically. You can send a query string and optionally include conversation history or authentication details. ```APIDOC ## POST /agent/query ### Description Query the agent via API with a given text query. Supports sending conversation history and authentication credentials. ### Method POST ### Endpoint `/agent/query` ### Parameters #### Request Body - **query** (string) - Required - The text query to send to the agent. - **history** (array[object]) - Optional - A list of previous messages to maintain conversation context. Each object should have `role` (string: 'user' or 'assistant') and `content` (string). - **auth** (object) - Optional - Authentication details. Can be a JSON object with keys like `api-key` or `Authorization` (for Bearer tokens). ### Request Example (JSON Body) ```json { "query": "What endpoints are available?", "history": [ {"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi there! How can I help you?"} ], "auth": { "api-key": "your-api-key-here" } } ``` ### Response #### Success Response (200) - **query** (string) - The original query sent. - **response** (string) - The agent's textual response. - **status** (string) - The status of the operation (e.g., 'success'). - **error** (string | null) - Any error message if the operation failed. - **history** (array[object]) - The updated conversation history. #### Response Example ```json { "query": "What endpoints are available?", "response": "This API has the following endpoints...", "status": "success", "error": null, "history": [ {"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi there! How can I help you?"}, {"role": "user", "content": "What endpoints are available?"}, {"role": "assistant", "content": "This API has the following endpoints..."} ] } ``` ``` -------------------------------- ### Default Agent Routes API Reference Source: https://context7.com/orco82/fastapi-agent/llms.txt When `include_router=True` is set for the FastAPI Agent, it automatically adds two useful routes: `/agent/query` for programmatic API queries and `/agent/chat` for a web-based chat interface. ```APIDOC ## Default Agent Routes API Reference When `include_router=True`, FastAPIAgent adds two routes: 1. **/agent/query**: For API queries. 2. **/agent/chat**: For a web UI chat interface. ### POST /agent/query Allows programmatic querying of the agent. See the detailed documentation for `/agent/query` above. ### GET /agent/chat Provides a web-based chat interface for interacting with the agent. Simply open this URL in your browser. ### Example Usage (curl) **Query the agent via API:** ```bash curl -X POST "http://localhost:8000/agent/query" \ -H "Content-Type: application/json" \ -d '{"query": "What endpoints are available?"}' ``` **Query with conversation history:** ```bash curl -X POST "http://localhost:8000/agent/query" \ -H "Content-Type: application/json" \ -d '{ "query": "Tell me more about the first endpoint", "history": [ {"role": "user", "content": "What endpoints are available?"}, {"role": "assistant", "content": "This API has GET /users and POST /users..."} ] }' ``` **Query with authentication (API Key):** ```bash curl -X POST "http://localhost:8000/agent/query" \ -H "Content-Type: application/json" \ -H 'auth: {"api-key": "your-api-key-here"}' \ -d '{"query": "Show me all protected endpoints"}' ``` **Query with authentication (Bearer Token):** ```bash curl -X POST "http://localhost:8000/agent/query" \ -H "Content-Type: application/json" \ -H 'auth: {"Authorization": "Bearer your-token-here"}' \ -d '{"query": "Access the secure data endpoint"}' ``` **Access the web chat interface:** Open in browser: `http://localhost:8000/agent/chat` ``` -------------------------------- ### Detect Authentication Patterns in FastAPI Source: https://context7.com/orco82/fastapi-agent/llms.txt Analyzes FastAPI route dependencies to detect various authentication patterns like Bearer tokens, API keys (header/query), HTTP Basic, and custom headers. It provides both a convenience function `detect_auth` and a class `AuthenticationDetector` for more granular control. Dependencies include FastAPI and specific security modules. ```python from fastapi import FastAPI, Depends, Security from fastapi.security import APIKeyHeader, HTTPBearer, HTTPBasic, APIKeyQuery from fastapi_agent.fastapi_auth import ( AuthenticationDetector, detect_auth, AuthType, AuthConfig, ) app = FastAPI(title="Auth Detection Example") # Various auth schemes api_key_header = APIKeyHeader(name="X-API-Key") bearer_scheme = HTTPBearer() basic_scheme = HTTPBasic() api_key_query = APIKeyQuery(name="api_key") @app.get("/bearer-auth") async def bearer_endpoint(credentials = Security(bearer_scheme)): """Endpoint using Bearer token authentication""" return {"auth": "bearer"} @app.get("/api-key-auth") async def api_key_endpoint(api_key: str = Security(api_key_header)): """Endpoint using API key header authentication""" return {"auth": "api_key"} @app.get("/query-auth") async def query_auth_endpoint(api_key: str = Security(api_key_query)): """Endpoint using API key query parameter""" return {"auth": "query"} @app.get("/basic-auth") async def basic_endpoint(credentials = Security(basic_scheme)): """Endpoint using HTTP Basic authentication""" return {"auth": "basic"} @app.get("/public") async def public_endpoint(): """Public endpoint without authentication""" return {"auth": "none"} # Detect authentication using convenience function detected_auth: AuthConfig = detect_auth(app) print(f"Primary Auth Type: {detected_auth.auth_type}") print(f"Parameter Name: {detected_auth.parameter_name}") print(f"Header Name: {detected_auth.header_name}") # Or use the detector class for more control detector = AuthenticationDetector(app) # Get the detected primary auth pattern (uses voting algorithm) primary_auth = detector.detected_auth print(f"\nDetected Primary Auth: {primary_auth.auth_type.value}") # Auth type enum values: # AuthType.NONE - No authentication # AuthType.API_KEY_HEADER - API key in header # AuthType.API_KEY_QUERY - API key in query string # AuthType.HTTP_BEARER - Bearer token # AuthType.HTTP_BASIC - HTTP Basic auth # AuthType.CUSTOM_HEADER - Custom header pattern # Auth strength ranking (used for tie-breaking): # HTTP_BEARER (4) > API_KEY_HEADER (3) > API_KEY_QUERY (2) > HTTP_BASIC (1) > CUSTOM_HEADER (0) > NONE (-1) ``` -------------------------------- ### Control Agent Route Access with FastAPI Agent Source: https://github.com/orco82/fastapi-agent/blob/main/README.md Shows how to specify which routes the FastAPI Agent can access using `ignore_routes` or `allow_routes`. This is crucial for security and controlling agent behavior. Routes are specified as a list of strings in 'METHOD:/path' format. ```python FastAPIAgent( app, model="openai:gpt-4.1-mini", base_url="https://localhost:8000", ignore_routes=["DELETE:/users/{user_id}"], include_router=True, ) ``` -------------------------------- ### FastAPIAgent with Authentication Handling Source: https://context7.com/orco82/fastapi-agent/llms.txt This snippet shows how to configure FastAPIAgent to work with authenticated FastAPI routes. The agent can automatically detect and inject authentication credentials (like API keys or Bearer tokens) when making calls to protected endpoints. This ensures secure interaction with your API. ```python from fastapi import FastAPI, Depends, HTTPException, Security from fastapi.security import APIKeyHeader from fastapi_agent import FastAPIAgent app = FastAPI(title="Secured API") # Define API key security api_key_header = APIKeyHeader(name="api-key") API_KEY = "secret-api-key-12345" async def verify_api_key(api_key: str = Security(api_key_header)): if api_key != API_KEY: raise HTTPException(status_code=401, detail="Invalid API key") return api_key # Protected route @app.get("/secure-data") async def get_secure_data(api_key: str = Depends(verify_api_key)): """Return sensitive data (requires API key)""" return {"data": "This is protected information", "status": "authenticated"} # Initialize agent with auth credentials FastAPIAgent( app, model="openai:gpt-4.1-mini", base_url="http://localhost:8000", auth={"api-key": API_KEY}, # For header-based API key auth # OR for Bearer token auth: # auth={"Authorization": "Bearer your-token-here"}, include_router=True, ) # Query the agent with authentication (curl example): # curl -X POST "http://localhost:8000/agent/query" \ # -H "Content-Type: application/json" \ # -H 'auth: {"api-key": "secret-api-key-12345"}' \ # -d '{"query": "What secure data is available?"}' ``` -------------------------------- ### Create Custom AI Agent Chat Endpoints Source: https://context7.com/orco82/fastapi-agent/llms.txt Implement custom API endpoints that directly use the `agent.chat()` method, bypassing the default `/agent/query` route. This allows for tailored request/response handling and conversation history management. ```python import asyncio from fastapi import FastAPI from pydantic import BaseModel from typing import Any, Optional, List from fastapi_agent import FastAPIAgent app = FastAPI(title="Custom Agent Routes") @app.get("/items") async def get_items(): """Get all items""" return [{"id": 1, "name": "Widget"}, {"id": 2, "name": "Gadget"}] # Initialize agent WITHOUT default router agent = FastAPIAgent( app, model="openai:gpt-4.1-mini", include_router=False, # Don't add default routes ) # Custom request/response models class ChatRequest(BaseModel): query: str conversation_history: Optional[List[dict]] = None class ChatResponse(BaseModel): answer: str history: List[dict] status: str = "success" # Custom endpoint with conversation history support @app.post("/api/chat", response_model=ChatResponse, tags=["AI Chat"]) async def custom_chat(request: ChatRequest): """Custom chat endpoint with history tracking""" history = request.conversation_history or [] response, updated_history = await agent.chat(request.query, history) return ChatResponse( answer=response, history=updated_history, ) # Programmatic usage example async def query_agent(): questions = [ "What endpoints are available?", "How can I get item details?", "What format does the items endpoint return?", ] history = [] for question in questions: print(f"\nQ: {question}") response, history = await agent.chat(question, history) print(f"A: {response}") # asyncio.run(query_agent()) ``` -------------------------------- ### AuthenticationDetector Class Source: https://context7.com/orco82/fastapi-agent/llms.txt This section details the AuthenticationDetector class, which analyzes FastAPI route dependencies to detect various authentication patterns like Bearer tokens, API keys (header/query), HTTP Basic, and custom headers. ```APIDOC ## AuthenticationDetector Class Detects authentication patterns in FastAPI applications by analyzing route dependencies. Supports Bearer tokens, API keys (header/query), HTTP Basic, and custom headers. ### Supported Authentication Types: - Bearer tokens - API keys (in header or query parameters) - HTTP Basic authentication - Custom headers ### Usage: ```python from fastapi import FastAPI from fastapi_agent.fastapi_auth import AuthenticationDetector, detect_auth, AuthType app = FastAPI() # Example endpoints (not shown here for brevity) # Detect authentication using a convenience function detected_auth = detect_auth(app) print(f"Primary Auth Type: {detected_auth.auth_type}") # Or use the detector class for more control detector = AuthenticationDetector(app) primary_auth = detector.detected_auth print(f"Detected Primary Auth: {primary_auth.auth_type.value}") ``` ### AuthType Enum Values: - `AuthType.NONE`: No authentication - `AuthType.API_KEY_HEADER`: API key in header - `AuthType.API_KEY_QUERY`: API key in query string - `AuthType.HTTP_BEARER`: Bearer token - `AuthType.HTTP_BASIC`: HTTP Basic auth - `AuthType.CUSTOM_HEADER`: Custom header pattern ### Auth Strength Ranking (for tie-breaking): - `HTTP_BEARER` (4) - `API_KEY_HEADER` (3) - `API_KEY_QUERY` (2) - `HTTP_BASIC` (1) - `CUSTOM_HEADER` (0) - `NONE` (-1) ``` -------------------------------- ### Filter AI Agent Routes with ignore_routes and allow_routes Source: https://context7.com/orco82/fastapi-agent/llms.txt Control which API routes an AI agent can access using either a blacklist (`ignore_routes`) or a whitelist (`allow_routes`). Routes are defined as 'METHOD:/path'. This prevents the agent from executing sensitive operations. ```python from fastapi import FastAPI from fastapi_agent import FastAPIAgent app = FastAPI(title="Filtered API") @app.get("/users") async def list_users(): """List all users""" return [{"id": 1, "name": "Alice"}] @app.delete("/users/{user_id}") async def delete_user(user_id: int): """Delete a user (dangerous operation)""" return {"deleted": user_id} @app.post("/admin/reset") async def admin_reset(): """Admin-only reset operation""" return {"status": "reset complete"} # Option 1: Exclude specific dangerous routes FastAPIAgent( app, model="openai:gpt-4.1-mini", ignore_routes=[ "DELETE:/users/{user_id}", # Prevent agent from deleting users "POST:/admin/reset", # Prevent agent from admin operations ], include_router=True, ) # Option 2: Only allow specific safe routes (whitelist) # FastAPIAgent( # app, # model="openai:gpt-4.1-mini", # allow_routes=[ # "GET:/users", # Only allow listing users # "GET:/users/{user_id}", # Only allow getting single user # ], # include_router=True, # ) ``` -------------------------------- ### Filter Routes for FastAPI Agent Access Source: https://github.com/orco82/fastapi-agent/blob/main/CLAUDE.md Control which routes the FastAPI Agent can access by either ignoring specific routes or whitelisting only certain routes. The format for specifying routes is `"METHOD:/path"`. ```python FastAPIAgent( app, ignore_routes=["DELETE:/users/{user_id}"], # Exclude specific routes # OR allow_routes=["GET:/users", "POST:/users"] # Whitelist only these routes ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.