### Install Dependencies and Run Local Development Server Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/INDEX.md Installs project dependencies, copies the environment file, and starts the CLI or endpoint for local development. ```bash pip install -r requirements.txt cp .env.example .env # Edit .env with your credentials python cli.py # CLI python github_agent_endpoint.py # Endpoint ``` -------------------------------- ### Clone Repository (Python) Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/README.md Clone the repository to your local machine to begin setup. This is the first step for both Python and Docker installations. ```bash git clone https://github.com/coleam00/ottomator-agents.git cd ottomator-agents/pydantic-github-agent ``` -------------------------------- ### Setup GitHubDeps for Agent Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/api-reference.md Example of setting up the GitHubDeps dataclass with an httpx.AsyncClient and a GitHub token retrieved from environment variables. This is typically done before running the agent. ```python import httpx import os from github_agent import GitHubDeps async def setup(): async with httpx.AsyncClient() as client: deps = GitHubDeps( client=client, github_token=os.getenv('GITHUB_TOKEN') ) # Pass deps to agent.run() ``` -------------------------------- ### Minimal CLI Configuration Example Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/configuration.md A minimal example demonstrating how to set environment variables directly for CLI usage. GITHUB_TOKEN can be omitted if working with public repositories. ```bash OPEN_ROUTER_API_KEY=sk-or-your-key LLM_MODEL=gpt-3.5-turbo # GITHUB_TOKEN is optional; omit for public repos only ``` -------------------------------- ### Example .env File for Configuration Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/configuration.md An example .env file showing the required environment variables for configuring the GitHub agent, including API keys and model settings. ```bash # GitHub API GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxx # LLM Configuration OPEN_ROUTER_API_KEY=sk-or-xxxxxxxxxxxxxxxxxxxx LLM_MODEL=deepseek/deepseek-chat # Endpoint-only configuration SUPABASE_URL=https://project.supabase.co SUPABASE_SERVICE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... API_BEARER_TOKEN=sk_local_test_token # Optional LOGFIRE_TOKEN=your_logfire_token ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/README.md Install the necessary Python packages for the agent. It is recommended to use a virtual environment for this step. ```bash pip install -r requirements.txt ``` -------------------------------- ### Analyzing Multiple Repositories Example Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/cli-reference.md Shows how to use the agent to compare the structure or content of multiple GitHub repositories within a single query. ```shell > Compare the structure of https://github.com/vuejs/vue and https://github.com/angular/angular (Agent can analyze both repositories in a single query) ``` -------------------------------- ### Example CLI Queries Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/README.md Sample queries you can use with the command-line interface to analyze GitHub repositories. These demonstrate the agent's capabilities in exploring repository structure and content. ```text What's the structure of repository https://github.com/username/repo? Show me the contents of the main Python file in https://github.com/username/repo What are the key features of repository https://github.com/username/repo? ``` -------------------------------- ### Example JSON Responses Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/types.md Illustrates the JSON format for successful and failed agent responses. ```json { "success": true } ``` ```json { "success": false } ``` -------------------------------- ### Create GitHubDeps Instance Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/types.md Example of how to instantiate the GitHubDeps class. It requires an active httpx.AsyncClient and can be configured with a GitHub token from environment variables. ```python import httpx import os from github_agent import GitHubDeps async with httpx.AsyncClient() as client: deps = GitHubDeps( client=client, github_token=os.getenv('GITHUB_TOKEN') ) ``` -------------------------------- ### GitHub Agent Usage Example Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/api-reference.md Demonstrates how to use the GitHub Agent to query repository information. Ensure GITHUB_TOKEN is set in your environment variables. ```python import asyncio import httpx import os from github_agent import github_agent, GitHubDeps from dotenv import load_dotenv load_dotenv() async def main(): async with httpx.AsyncClient() as client: deps = GitHubDeps( client=client, github_token=os.getenv('GITHUB_TOKEN') ) result = await github_agent.run( "What are the main features of https://github.com/pallets/flask?", deps=deps ) print(result.data) asyncio.run(main()) ``` -------------------------------- ### Example POST Request Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/endpoints.md Demonstrates how to make a POST request to the agent endpoint using curl, including authentication and a sample JSON payload. ```bash curl -X POST http://localhost:8001/api/pydantic-github-agent \ -H "Authorization: Bearer your_bearer_token" \ -H "Content-Type: application/json" \ -d '{ "query": "What is the main structure of https://github.com/pydantic/pydantic?", "user_id": "user_12345", "request_id": "req_67890", "session_id": "sess_abcde" }' ``` -------------------------------- ### Query Repository Structure Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/cli-reference.md Example of querying the structure of a given GitHub repository. The agent will list the main directories and files. ```text > What's the structure of repository https://github.com/python/cpython? [Using https://github.com/python/cpython] The CPython repository has the following main structure: 📁 Lib 📁 Modules 📁 Objects 📁 Parser 📁 Programs 📁 Tools 📄 README.rst 📄 setup.py ... (and many more files) ``` -------------------------------- ### Example Success Response Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/endpoints.md Shows the expected JSON response when the agent request is processed successfully. ```json { "success": true } ``` -------------------------------- ### Run the GitHub Agent CLI Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/cli-reference.md This is the main entry point for the CLI application. It initializes the CLI and starts the chat interface. Run this command to launch the agent. ```python async def main(): cli = CLI() await cli.chat() if __name__ == "__main__": asyncio.run(main()) ``` ```bash python cli.py ``` -------------------------------- ### API POST /api/pydantic-github-agent Success Response Example Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/INDEX.md Example JSON response for a successful processing of a query via the POST /api/pydantic-github-agent endpoint. ```json {"success": true} ``` -------------------------------- ### Multi-turn Conversations Example Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/cli-reference.md Demonstrates how the agent maintains context across multiple turns in a conversation, allowing follow-up questions about previously discussed repositories. ```shell > What's in https://github.com/facebook/react? [Repository information] > Now show me the package.json file (Agent remembers the previous repository) > What's the main entry point? (Agent can reference previous context) ``` -------------------------------- ### API POST /api/pydantic-github-agent Request Example Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/INDEX.md Example JSON payload for the POST /api/pydantic-github-agent endpoint, used to initiate a GitHub analysis query. ```json { "query": "What's the structure of https://github.com/pydantic/pydantic?", "user_id": "user_123", "request_id": "req_456", "session_id": "sess_789" } ``` -------------------------------- ### Query Repository Details Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/cli-reference.md Example of requesting detailed information about a GitHub repository. The agent provides metadata such as description, size, stars, and creation/update dates. ```text > What are the details about https://github.com/kubernetes/kubernetes? [Using https://github.com/kubernetes/kubernetes] Repository: kubernetes/kubernetes Description: Production-Grade Container Orchestration Size: 850.5MB Stars: 110000 Language: Go Created: 2014-06-06T22:56:04Z Last Updated: 2026-06-19T10:30:45Z ``` -------------------------------- ### Instantiate and Use AsyncClient Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/types.md Demonstrates how to create an instance of AsyncClient using an asynchronous context manager and make a GET request with custom headers. The client connection is automatically managed and closed upon exiting the context. ```python async with httpx.AsyncClient() as client: response = await client.get(url, headers=headers) ``` -------------------------------- ### Example Row for Messages Table Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/configuration.md An example of a row entry in the 'messages' table, demonstrating the structure and data types for a human-initiated message. ```json { "id": 1, "session_id": "sess_abc123", "message": { "type": "human", "content": "What is the structure of https://github.com/pydantic/pydantic?" }, "created_at": "2026-06-19T10:30:00Z", "created_by": "system" } ``` -------------------------------- ### Dockerfile for GitHub Agent Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/configuration.md This Dockerfile sets up the Python environment, installs dependencies, copies the project code, exposes the necessary port, and defines the entry point for the GitHub agent. ```dockerfile FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . EXPOSE 8001 CMD ["python", "github_agent_endpoint.py"] ``` -------------------------------- ### Query File Content Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/cli-reference.md Example of requesting the content of a specific file from a GitHub repository. The agent will display the beginning of the file's content. ```text > Show me the README from https://github.com/nodejs/node [Using https://github.com/nodejs/node] # Node.js Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. ... ``` -------------------------------- ### Tool-Level Error Handling Example Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/architecture.md Illustrates how tools return error messages as strings. The agent can then interpret these messages for retries or user feedback. ```python def get_repo_info(...) -> str: if invalid_url: return "Invalid GitHub URL format" if api_error: return f"Failed to get repository info: {error}" ``` -------------------------------- ### Start Interactive GitHub Agent CLI Session Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/cli-reference.md Initiates an interactive session with the GitHub Agent CLI. Type 'quit' to exit the session. ```bash $ python cli.py GitHub Agent CLI (type 'quit' to exit) Enter your message: ``` -------------------------------- ### Environment Variables for .env File Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/configuration.md Example of how to set required environment variables in a .env file for the CLI. Ensure you replace placeholder values with your actual credentials. ```bash # .env file GITHUB_TOKEN=your_github_token OPEN_ROUTER_API_KEY=your_openrouter_key LLM_MODEL=deepseek/deepseek-chat # or any other model ``` -------------------------------- ### Unit Test for get_repo_info Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/architecture.md Tests the `get_repo_info` function independently. Ensure `httpx` is installed and available for mocking HTTP requests. ```python async def test_get_repo_info(): async with httpx.AsyncClient() as client: deps = GitHubDeps(client=client, github_token=None) ctx = RunContext(deps=deps) result = await get_repo_info(ctx, "https://github.com/pydantic/pydantic") assert "Repository:" in result ``` -------------------------------- ### API POST /api/pydantic-github-agent Failure Response Example Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/INDEX.md Example JSON response indicating a failure in processing a query via the POST /api/pydantic-github-agent endpoint. ```json {"success": false} ``` -------------------------------- ### Handle API Failures for Repository Info Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/cli-reference.md This example shows the error message when the CLI fails to retrieve repository information due to an invalid repository path. ```text > What's in https://github.com/nonexistent/repo? [Using https://github.com/nonexistent/repo?] Failed to get repository info: {"message":"Not Found"...} ``` -------------------------------- ### GitHub Agent Endpoint Module Execution Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/modules.md Starts the FastAPI server using uvicorn when the module is run directly. ```python if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8001) ``` -------------------------------- ### Example Valid Agent Request Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/errors.md A sample JSON object demonstrating a correctly formatted request to the agent, including all required fields such as query, user_id, request_id, and session_id. ```json { "query": "What is the size of https://github.com/pydantic/pydantic?", "user_id": "user_123", "request_id": "req_456", "session_id": "sess_789" } ``` -------------------------------- ### Example AgentRequest JSON Payload Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/types.md Illustrates a valid JSON payload for an AgentRequest. All fields are required and must be non-empty strings. ```json { "query": "What are the main features of https://github.com/pydantic/pydantic?", "user_id": "user_123", "request_id": "req_456", "session_id": "sess_789" } ``` -------------------------------- ### Example Failure Response Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/endpoints.md Shows the expected JSON response when an error occurs during agent request processing. ```json { "success": false } ``` -------------------------------- ### Build and Run Docker Image Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/README.md Build the Docker image and run the agent as a container. This method avoids local Python installations and dependencies. The API endpoint will be available at http://localhost:8001. ```bash docker build -t github-agent . docker run -p 8001:8001 --env-file .env github-agent ``` -------------------------------- ### Get Repository Information Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/INDEX.md Retrieves metadata for a given GitHub repository. This tool is queried automatically by the agent based on user questions. ```python # Queried automatically by agent based on user question # Returns: "Repository: owner/repo\nSize: 123.4MB\nStars: 5000..." ``` -------------------------------- ### Get Repository Structure Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/INDEX.md Retrieves the directory tree structure of a GitHub repository, including emoji icons for directories and files. ```python # Returns: # 📁 src # 📄 src/main.py # 📁 tests # 📄 tests/test_api.py ``` -------------------------------- ### Run FastAPI Endpoint Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/README.md Start the agent as a FastAPI API endpoint. This allows integration with tools like the oTTomator Live Agent Studio. The endpoint will be accessible at http://localhost:8001. ```python python github_agent_endpoint.py ``` -------------------------------- ### Endpoint-Level Error Handling Example Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/architecture.md Demonstrates how the endpoint catches exceptions during agent execution. It logs the error and returns a success flag of false, while still maintaining a 200 OK status. ```python try: result = await github_agent.run(...) except Exception as e: await store_message( session_id=request.session_id, message_type="ai", content="I apologize, but I encountered an error...", data={"error": str(e), "request_id": request.request_id} ) return AgentResponse(success=False) ``` -------------------------------- ### Get Repository Information Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/api-reference.md Demonstrates how the get_repo_info tool is invoked internally by the agent to retrieve and format metadata for a given GitHub repository URL. This function is automatically called when the agent processes a user query related to repository details. ```python from pydantic_ai import RunContext from github_agent import github_agent, GitHubDeps # Called automatically when agent processes a user query # User query: "What's the size and description of https://github.com/pydantic/pydantic?" # Tool is invoked internally by the agent, returns: # Repository: pydantic/pydantic # Description: Data validation using Python type annotations # Size: 12345.5MB # Stars: 25000 # Language: Python # Created: 2015-01-01T00:00:00Z # Last Updated: 2026-06-19T12:00:00Z ``` -------------------------------- ### Get Repository Structure Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/api-reference.md Fetches the directory tree of a GitHub repository. It attempts to use the 'main' branch first and falls back to 'master'. Excludes common build and version control directories. ```python async def get_repo_structure(ctx: RunContext[GitHubDeps], github_url: str) -> str: # User query: "Show me the structure of https://github.com/fastapi/fastapi" # Returns: # 📁 docs # 📁 docs/en # 📄 docs/en/mkdocs.yml # 📁 fastapi # 📄 fastapi/__init__.py # 📄 fastapi/applications.py # 📁 tests # 📄 tests/test_api.py ``` -------------------------------- ### Creating and Building Message History Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/types.md Provides an example of creating user and model messages with specific parts, and then assembling them into a conversation history list. The `ModelMessage` type is a union of request and response types. ```python # Create a user message user_msg = ModelRequest(parts=[ UserPromptPart(content="What is the repository size?") ]) # Create a model response message model_msg = ModelResponse(parts=[ TextPart(content="The repository size is 12.5 MB") ]) # Build history messages: List[ModelMessage] = [user_msg, model_msg] ``` -------------------------------- ### Example GitHub API Error Responses Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/errors.md Shows common JSON error responses from the GitHub API when fetching repository information. These include 'Not Found', 'API rate limit exceeded', and 'Bad credentials'. ```json {"message":"Not Found","documentation_url":"https://docs.github.com/rest/reference/repos#get-a-repository"} {"message":"API rate limit exceeded for user ID 12345.","documentation_url":"https://docs.github.com/rest"} {"message":"Bad credentials","documentation_url":"https://docs.github.com/rest"} ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/cli-reference.md Copy the template and edit the .env file with your GitHub and OpenRouter API keys, and specify the LLM model. ```bash cp .env.example .env # Edit .env with your keys GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx OPEN_ROUTER_API_KEY=sk-or-xxxxxxxxxxxxxxxxxxxx LLM_MODEL=deepseek/deepseek-chat ``` -------------------------------- ### Build and Run Docker Container Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/configuration.md Commands to build the Docker image and run the container, demonstrating how to pass environment variables via an .env file or explicit flags. ```bash # Build docker build -t github-agent . # Run with .env file docker run -p 8001:8001 --env-file .env github-agent # Run with explicit env vars docker run -p 8001:8001 \ -e GITHUB_TOKEN=xxx \ -e OPEN_ROUTER_API_KEY=xxx \ -e LLM_MODEL=deepseek/deepseek-chat \ -e SUPABASE_URL=xxx \ -e SUPABASE_SERVICE_KEY=xxx \ -e API_BEARER_TOKEN=xxx \ github-agent ``` -------------------------------- ### Supabase Client Initialization Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/modules.md Initializes the Supabase client using URL and service key from environment variables. ```python supabase: Client = create_client( os.getenv("SUPABASE_URL"), os.getenv("SUPABASE_SERVICE_KEY") ) ``` -------------------------------- ### Build Docker Image Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/INDEX.md Build a Docker image for the GitHub agent. This is the first step in deploying the agent using Docker. ```bash docker build -t github-agent . ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/README.md Set up your API keys and model preferences by renaming and editing the .env file. Ensure you have a GitHub token for private repositories and an OpenRouter API key. ```env GITHUB_TOKEN=your_github_token # Required for private repos OPEN_ROUTER_API_KEY=your_openrouter_api_key LLM_MODEL=your_chosen_model # e.g., deepseek/deepseek-chat SUPABASE_URL=your_supabase_url # Only needed for endpoint SUPABASE_SERVICE_KEY=your_supabase_key # Only needed for endpoint ``` -------------------------------- ### Context-Managed HTTP Client Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/architecture.md Demonstrates the use of `httpx.AsyncClient` as a context manager. This ensures proper cleanup of resources, connection pooling, and automatic handling of client lifecycle. ```python async with httpx.AsyncClient() as client: # Use client # Automatically cleaned up ``` -------------------------------- ### Get File Content Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/api-reference.md Retrieves the raw content of a specific file from a GitHub repository. It prioritizes the 'main' branch and falls back to 'master'. ```python async def get_file_content(ctx: RunContext[GitHubDeps], github_url: str, file_path: str) -> str: # User query: "Show me the README from https://github.com/nodejs/node" # Tool is called with: # github_url = "https://github.com/nodejs/node" # file_path = "README.md" # Returns: raw contents of the README.md file ``` -------------------------------- ### Query Repository via CLI Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/INDEX.md Interact with the GitHub agent using the command-line interface to ask questions about repositories. ```bash python cli.py > What's the structure of https://github.com/pydantic/pydantic? > Show me the README from https://github.com/pydantic/pydantic > quit ``` -------------------------------- ### Run Command Line Interface Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/README.md Execute the agent via its command-line interface for a direct interactive experience. This is useful for quick queries and testing. ```python python cli.py ``` -------------------------------- ### Get File Content Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/INDEX.md Retrieves the raw content of a specified file within a GitHub repository. Useful for accessing files like README.md or setup.py. ```python # Returns raw file contents from README.md, setup.py, etc. ``` -------------------------------- ### Agent Execution Flow Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/architecture.md This snippet shows the common execution flow for the agent, whether run via CLI or an endpoint. It demonstrates how to initialize dependencies and run the agent with a user query and optional message history. ```python async with httpx.AsyncClient() as client: deps = GitHubDeps(client=client, github_token=token) result = await github_agent.run( user_query, deps=deps, message_history=messages # Optional ) print(result.data) # Agent's response ``` -------------------------------- ### Create GitHubDeps Instance for Request Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/endpoints.md This snippet shows how to create a fresh GitHubDeps instance for each incoming request. It utilizes an httpx.AsyncClient and retrieves the GitHub token from environment variables. This ensures a new HTTP client and authentication context for each agent run. ```python async with httpx.AsyncClient() as client: deps = GitHubDeps( client=client, github_token=os.getenv("GITHUB_TOKEN") ) result = await github_agent.run( request.query, message_history=messages, deps=deps ) ``` -------------------------------- ### Instantiate OpenAIModel for Direct OpenAI Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/types.md Instantiate OpenAIModel for direct use with OpenAI, providing the model ID and API key. ```python model = OpenAIModel( 'gpt-4', api_key='your_openai_key' ) ``` -------------------------------- ### Tool Registration with Decorator Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/architecture.md Shows how tools are registered with the agent using the `@github_agent.tool` decorator. The tool's docstring serves as its description for the agent. ```python @github_agent.tool async def get_repo_info(...) -> str: """Tool description for agent.""" ``` -------------------------------- ### Import and Run CLI Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/modules.md Import the Command Line Interface (CLI) and run its chat functionality asynchronously. ```python from cli import CLI, main import asyncio async def run(): cli = CLI() await cli.chat() asyncio.run(run()) ``` -------------------------------- ### Test Individual GitHub Repository Tool Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/errors.md This snippet demonstrates how to test the 'get_repo_info' tool independently. It sets up necessary dependencies like an httpx client and GitHubDeps, and uses a RunContext to execute the tool with a repository URL. ```python import asyncio import httpx from github_agent import get_repo_info, GitHubDeps from pydantic_ai import RunContext async def test(): async with httpx.AsyncClient() as client: deps = GitHubDeps(client=client, github_token=None) ctx = RunContext(deps=deps) result = await get_repo_info(ctx, "https://github.com/pydantic/pydantic") print(result) asyncio.run(test()) ``` -------------------------------- ### Loading Environment Variables in Python Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/configuration.md Demonstrates how to load environment variables from a .env file into your Python script using the python-dotenv library. Provides default values for optional variables. ```python from dotenv import load_dotenv import os load_dotenv() # Loads from .env file # Variables are now available github_token = os.getenv('GITHUB_TOKEN') llm_model = os.getenv('LLM_MODEL', 'deepseek/deepseek-chat') ``` -------------------------------- ### Programmatic Usage: Individual Component Integration Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/cli-reference.md Demonstrates integrating individual components of the GitHub agent, such as the `github_agent.run` function, for more granular control over repository analysis. ```python import asyncio import httpx from github_agent import github_agent, GitHubDeps async def query_repo(url: str, question: str): async with httpx.AsyncClient() as client: deps = GitHubDeps(client=client, github_token="token") result = await github_agent.run( f"{question} from {url}", deps=deps ) print(result.data) asyncio.run(query_repo("https://github.com/pydantic/pydantic", "What are the main features?")) ``` -------------------------------- ### Enable Logfire via Environment Variable Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/configuration.md Enable Logfire integration by setting the LOGFIRE_TOKEN environment variable. No other configuration is needed. ```bash LOGFIRE_TOKEN=your_logfire_token ``` -------------------------------- ### Initialize LLM with OpenRouter or OpenAI API Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/api-reference.md Initializes the LLM model. If OPEN_ROUTER_API_KEY is set, it uses the OpenRouter API; otherwise, it defaults to the direct OpenAI API. The default LLM model is 'deepseek/deepseek-chat'. ```python llm = os.getenv('LLM_MODEL', 'deepseek/deepseek-chat') model = OpenAIModel( llm, base_url = 'https://openrouter.ai/api/v1', api_key=os.getenv('OPEN_ROUTER_API_KEY') ) if os.getenv('OPEN_ROUTER_API_KEY', None) else OpenAIModel(llm) ``` -------------------------------- ### Key Library Versions Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/modules.md List of essential libraries and their pinned versions for ensuring compatibility. These versions have been tested together. ```text pydantic-ai==0.0.13 httpx==0.27.2 fastapi==0.115.6 supabase==2.11.0 uvicorn==0.34.0 python-dotenv==1.0.1 ``` -------------------------------- ### CLI Module Execution Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/modules.md Entry point for the cli.py module, initiating an asynchronous session using asyncio.run(main()). ```python if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Run Docker Container Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/INDEX.md Run the Docker container for the GitHub agent, mapping the port and specifying environment variables via an .env file for configuration. ```bash docker run -p 8001:8001 --env-file .env github-agent ``` -------------------------------- ### Import GitHub Agent Components Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/modules.md Import the main agent class, its dependencies, and utility functions for repository information. ```python from github_agent import github_agent, GitHubDeps, get_repo_info ``` -------------------------------- ### OpenAIModel Constructor Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/types.md Wrapper for OpenAI-compatible APIs. Allows configuration of model ID, base URL, and API key. ```APIDOC ## OpenAIModel ### Description LLM model wrapper for OpenAI-compatible APIs. ### Constructor Parameters #### Parameters - **model_id** (str) - Yes - Model identifier (e.g., `gpt-4`, `deepseek/deepseek-chat`) - **base_url** (str) - No - `https://api.openai.com/v1` - API endpoint URL - **api_key** (str) - No - API authentication key ### Usage Example ```python from pydantic_ai.models.openai import OpenAIModel # OpenRouter configuration model = OpenAIModel( 'deepseek/deepseek-chat', base_url='https://openrouter.ai/api/v1', api_key='your_openrouter_key' ) # Direct OpenAI model = OpenAIModel( 'gpt-4', api_key='your_openai_key' ) ``` ``` -------------------------------- ### Import OpenAIModel Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/types.md Import the OpenAIModel class from the pydantic_ai.models.openai library. ```python from pydantic_ai.models.openai import OpenAIModel ``` -------------------------------- ### Agent Constructor and Methods Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/types.md Generic agent type that can be parameterized with dependency types. Includes methods for running the agent and registering tools. ```APIDOC ## Agent ### Description Generic agent type: `Agent[GitHubDeps]` ### Constructor Parameters #### Parameters - **model** (OpenAIModel) - Yes - LLM model instance - **system_prompt** (str) - No - System instructions for the agent - **deps_type** (type) - No - Type of dependencies (GitHubDeps) - **retries** (int) - No - Number of retries for tool failures ### Instance Methods #### run ```python async def run( user_prompt: str, deps: T = None, message_history: List[ModelMessage] = None ) -> AgentRunResult ``` ### Generic Parameter #### Parameter - **GitHubDeps** - The dependency type injected into tools and context ### Decorator Methods #### tool ```python @agent.tool async def tool_name(ctx: RunContext[GitHubDeps], param: str) -> str: """Tool docstring.""" ``` Registers a function as a tool available to the agent. ``` -------------------------------- ### Instantiate OpenAIModel with OpenRouter Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/types.md Configure and instantiate OpenAIModel for use with OpenRouter, specifying the model ID, base URL, and API key. ```python model = OpenAIModel( 'deepseek/deepseek-chat', base_url='https://openrouter.ai/api/v1', api_key='your_openrouter_key' ) ``` -------------------------------- ### Exit the CLI Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/cli-reference.md Demonstrates how to exit the interactive CLI session by typing 'quit'. ```text > quit (Client closes and program exits) ``` -------------------------------- ### Query Repository via HTTP Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/INDEX.md Send POST requests to the agent's HTTP endpoint to query repository information. ```bash curl -X POST http://localhost:8001/api/pydantic-github-agent \ -H "Content-Type: application/json" \ -d '{ "query": "What is https://github.com/pydantic/pydantic?", "user_id": "user_1", "request_id": "req_1", "session_id": "sess_1" }' ``` -------------------------------- ### Server Configuration Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/endpoints.md Runs the FastAPI application using uvicorn on all network interfaces on port 8001. ```python uvicorn.run(app, host="0.0.0.0", port=8001) ``` -------------------------------- ### Customize System Prompt Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/modules.md Modify the `system_prompt` constant in `github_agent.py` to change the agent's core instructions. Recreate the agent instance after modification. ```python system_prompt = """ Your custom instructions here. """ ``` -------------------------------- ### Model Selection Logic Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/modules.md Configures the OpenAIModel based on the presence of an OPEN_ROUTER_API_KEY. Uses OpenRouter if the key is set, otherwise defaults to direct OpenAI API. ```python model = OpenAIModel( llm, base_url='https://openrouter.ai/api/v1', api_key=os.getenv('OPEN_ROUTER_API_KEY') ) if os.getenv('OPEN_ROUTER_API_KEY', None) else OpenAIModel(llm) ``` -------------------------------- ### CLI __init__ Method Signature Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/cli-reference.md Shows the signature for the CLI class constructor, indicating no arguments are taken. ```python def __init__(self) -> None ``` -------------------------------- ### RunContext Type Hint Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/types.md Shows how to import and use the RunContext type for dependency injection in tool functions. Access dependencies via the `ctx.deps` attribute. ```python from pydantic_ai import RunContext ``` -------------------------------- ### Using RunContext in a Tool Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/types.md Demonstrates accessing client and GitHub token dependencies within a tool function using the RunContext. The generic parameter `T` is typically `GitHubDeps`. ```python @github_agent.tool async def get_repo_info(ctx: RunContext[GitHubDeps], github_url: str) -> str: # Access dependencies via ctx.deps client = ctx.deps.client github_token = ctx.deps.github_token ``` -------------------------------- ### Tool Interface Signature Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/modules.md Illustrates the signature for agent tools, which are asynchronous functions decorated with `@github_agent.tool`. They receive a `RunContext` and parameters, returning a string response. ```python @github_agent.tool async def tool_name( ctx: RunContext[GitHubDeps], parameter: str ) -> str: """Tool description.""" ``` -------------------------------- ### Run HTTP Endpoint with Uvicorn Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/INDEX.md Alternatively, use Uvicorn to run the HTTP endpoint, specifying the port for API-based agent access. ```bash uvicorn github_agent_endpoint:app --port 8001 ``` -------------------------------- ### LLM Model Selection Logic Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/configuration.md This Python code snippet demonstrates how the LLM model is selected based on environment variables. It prioritizes OpenRouter if an API key is provided, otherwise falls back to direct OpenAI. ```python llm = os.getenv('LLM_MODEL', 'deepseek/deepseek-chat') model = OpenAIModel( llm, base_url='https://openrouter.ai/api/v1', api_key=os.getenv('OPEN_ROUTER_API_KEY') ) if os.getenv('OPEN_ROUTER_API_KEY', None) else OpenAIModel(llm) ``` -------------------------------- ### CLI Class Definition Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/modules.md Defines the CLI class with initialization and chat methods for interactive agent sessions. ```python class CLI: def __init__(self) async def chat(self) ``` -------------------------------- ### Programmatic Usage: Basic CLI Class Integration Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/cli-reference.md Illustrates how to instantiate and use the CLI class within other Python scripts to leverage its chat functionality and maintain message history. ```python import asyncio from cli import CLI async def custom_query(): cli = CLI() # Message history is maintained await cli.chat() asyncio.run(custom_query()) ``` -------------------------------- ### get_repo_info Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/api-reference.md Retrieves repository metadata from GitHub API including size, description, stars, language, and timestamps. ```APIDOC ## get_repo_info ### Description Retrieves repository metadata from GitHub API including size, description, stars, language, and timestamps. ### Signature ```python async def get_repo_info(ctx: RunContext[GitHubDeps], github_url: str) -> str ``` ### Parameters | Parameter | Type | Required | Default | Description | |---|---|---|---|---| | ctx | `RunContext[GitHubDeps]` | Yes | — | Agent execution context containing HTTP client and GitHub token | | github_url | `str` | Yes | — | GitHub repository URL (e.g., `https://github.com/owner/repo` or `git@github.com:owner/repo.git`) | ### Returns `str` — Formatted string containing repository information with fields: Repository name, description, size in MB, star count, primary language, creation date, and last update date. Returns error message if URL is invalid or API call fails. ### Throws/Fails - Invalid URL format: returns `"Invalid GitHub URL format"` - API failure: returns `"Failed to get repository info: {response.text}"` ``` -------------------------------- ### Import GitHub Agent Endpoint Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/modules.md Import the FastAPI application for the GitHub agent endpoint. This is typically used with a server like uvicorn. ```python from github_agent_endpoint import app # Use with uvicorn or FastAPI server ``` -------------------------------- ### Dependency Injection in Tool Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/architecture.md Illustrates dependency injection within a tool function. The `GitHubDeps` object, containing runtime dependencies like an HTTP client and token, is accessed via the `RunContext`. ```python @github_agent.tool async def get_repo_info(ctx: RunContext[GitHubDeps], github_url: str) -> str: client = ctx.deps.client # Injected dependency token = ctx.deps.github_token ``` -------------------------------- ### GitHub Agent Data Flow Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/architecture.md Illustrates the data flow within the CLI module, showing how user input is processed by the agent and how conversation history is managed. ```text User Input → CLI.chat() → github_agent.run() → Tool calls → Agent response → Display ↓ History stored in memory ``` -------------------------------- ### Endpoint Environment Variables Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/configuration.md Set these environment variables in a .env file for the GitHub Agent endpoint. Ensure you replace placeholder values with your actual credentials and tokens. ```bash # .env file for endpoint GITHUB_TOKEN=your_github_token OPEN_ROUTER_API_KEY=your_openrouter_key LLM_MODEL=deepseek/deepseek-chat SUPABASE_URL=https://your-project.supabase.co SUPABASE_SERVICE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... API_BEARER_TOKEN=your_bearer_token ``` -------------------------------- ### Load Environment Variables Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/cli-reference.md The CLI automatically loads environment variables from the .env file using dotenv. ```python from dotenv import load_dotenv load_dotenv() ``` -------------------------------- ### Fetch Repository Structure with Fallback Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/errors.md Attempts to retrieve the repository's file structure from the GitHub API, first trying the 'main' branch and falling back to the 'master' branch if the initial request fails. This handles cases where a repository might not have a 'main' branch. ```python # Try main branch first response = await ctx.deps.client.get( f'https://api.github.com/repos/{owner}/{repo}/git/trees/main?recursive=1', headers=headers ) # Fall back to master if main fails if response.status_code != 200: response = await ctx.deps.client.get( f'https://api.github.com/repos/{owner}/{repo}/git/trees/master?recursive=1', headers=headers ) if response.status_code != 200: return f"Failed to get repository structure: {response.text}" ``` -------------------------------- ### Unit Test for GitHub Repository Information Source: https://github.com/coleam00/pydantic-ai-github-agent/blob/main/_autodocs/INDEX.md An asynchronous Python unit test using httpx to fetch repository information. It asserts that the result contains 'Repository:' and prints the output. Requires github_agent and pydantic_ai libraries. ```python import asyncio import httpx from github_agent import get_repo_info, GitHubDeps from pydantic_ai import RunContext async def test(): async with httpx.AsyncClient() as client: deps = GitHubDeps(client=client, github_token=None) ctx = RunContext(deps=deps) result = await get_repo_info(ctx, "https://github.com/pydantic/pydantic") assert "Repository:" in result print(result) asyncio.run(test()) ```