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

https://github.com/langchain-samples/agent-oauth-example

This project demonstrates the new **Agent OAuth Authentication** capabilities in LangSmith, showcasing how to build intelligent agents that can securely authen…
https://github.com/langchain-samples/agent-oauth-example

authentication intermediate langgraph

Last synced: 7 days ago
JSON representation

This project demonstrates the new **Agent OAuth Authentication** capabilities in LangSmith, showcasing how to build intelligent agents that can securely authen…

Awesome Lists containing this project

README

          

# LangSmith Agent OAuth Authentication Example

This project demonstrates the new **Agent OAuth Authentication** capabilities in LangSmith, showcasing how to build intelligent agents that can securely authenticate with external services like GitHub and access user data on-demand.

## πŸš€ Features

- **Seamless OAuth Integration**: Agents automatically handle OAuth flows when accessing protected resources
- **Middleware-Based Authentication**: Uses LangChain's new middleware system to intercept tool calls and trigger authentication
- **Interrupt-Driven Flow**: Agents pause execution to surface OAuth URLs to users, then resume after authentication
- **Secure Token Management**: OAuth tokens are securely stored in runtime context and automatically used for API calls
- **GitHub API Integration**: Example tools for accessing user info, repositories, and followers

## πŸ—οΈ Architecture

This example uses:
- **LangChain v1** with `create_agent` for rapid agent development
- **LangGraph middleware** (`@after_model`) to customize post-model behavior
- **LangSmith OAuth** for secure authentication flows
- **GitHub OAuth App** for external service integration

## πŸ”„ OAuth Interrupt Flow

When the agent needs to access GitHub data, it automatically pauses execution and shows the OAuth URL to the user:

![Agent OAuth Interrupt Flow](assets/agent_oauth_interrupt.jpeg)

The agent will pause at the interrupt point, allowing users to complete the OAuth flow in their browser, then resume execution with authenticated access to GitHub APIs.

## πŸ“‹ Prerequisites

1. **LangSmith Account**: Sign up at [langsmith.com](https://langsmith.com)
2. **GitHub Account**: For creating OAuth applications
3. **Python 3.8+**: For running the agent
4. **Environment Variables**: API keys and configuration

## πŸ› οΈ Setup Instructions

### Step 1: Create GitHub OAuth Application

1. Go to [GitHub Settings > Developer Settings > OAuth Apps](https://github.com/settings/developers)
2. Click "New OAuth App"
3. Fill in the application details:
- **Application name**: `LangSmith Agent Auth Example`
- **Homepage URL**: `https://your-domain.com` (or `http://localhost:8000` for development)
- **Authorization callback URL**: `https://api.host.langchain.com/v2/auth/callback/agent-auth-github`
4. Save the application and note down the **Client ID** and **Client Secret**

### Step 2: Configure LangSmith OAuth Provider

1. Go to [LangSmith Settings > OAuth Providers](https://smith.langchain.com/settings/oauth-providers)
2. Click "Create OAuth Provider"
3. Configure the provider:
- **Provider ID**: `agent-auth-github`
- **Provider Name**: `GitHub`
- **Client ID**: (from GitHub OAuth App)
- **Client Secret**: (from GitHub OAuth App)
- **Authorization URL**: `https://github.com/login/oauth/authorize`
- **Token URL**: `https://github.com/login/oauth/access_token`
- **Scopes**: `repo,user`
4. Save the provider configuration

### Step 3: Install Dependencies

```bash
pip install -r requirements.txt
```

### Step 4: Environment Configuration

Create a `.env` file with your API keys:

```bash
# LangSmith API Key (get from https://smith.langchain.com/settings)
LANGSMITH_API_KEY=your_langsmith_api_key_here

# OpenAI API Key (for the agent model)
OPENAI_API_KEY=your_openai_api_key_here

# Optional: LangSmith project for tracing
LANGCHAIN_TRACING_V2=true
LANGCHAIN_PROJECT=github-auth-example
```

## 🎯 How It Works

### 1. Agent Creation with Middleware

The agent is created using LangChain's `create_agent` with custom middleware:

```python
from langchain.agents import create_agent
from langchain.agents.middleware import after_model

# Define context schema for runtime
@dataclass
class Context:
github_token: str = None

# Authentication middleware
@after_model(can_jump_to=["end"])
async def auth_github(state: AgentState, runtime: Runtime[Context]) -> Dict[str, Any] | None:
# Check if GitHub tools are being called
# Trigger OAuth flow if needed
# Store token in runtime context

# Create agent with middleware
agent = create_agent(
model="openai:gpt-4o-mini",
tools=[get_github_user_info, get_github_repositories, get_github_followers],
middleware=[auth_github],
context_schema=Context,
)
```

### 2. OAuth Flow with Interrupts

When the agent needs to access GitHub data:

1. **Detection**: Middleware detects GitHub tool calls
2. **Interrupt**: Agent pauses execution and shows OAuth URL
3. **Authentication**: User completes OAuth flow in browser
4. **Resume**: Agent continues with authenticated access

```python
# In the middleware
if needs_auth and not runtime.context.github_token:
auth_result = await client.authenticate(
provider="agent-auth-github",
scopes=["repo", "user"],
user_id="user_123",
agent_scoped=False
)

if auth_result.needs_auth:
# Pause agent and show OAuth URL
interrupt(f"πŸ” GitHub authentication required. Please complete OAuth at: {auth_result.auth_url}")
else:
# Store token for API calls
runtime.context.github_token = auth_result.token
```

### 3. Authenticated Tool Execution

Tools automatically use the stored OAuth token:

```python
@tool
async def get_github_user_info(runtime: ToolRuntime) -> str:
headers = {
'Authorization': f'token {runtime.context.github_token}',
'Accept': 'application/vnd.github.v3+json'
}
# Make authenticated GitHub API calls
```

## πŸš€ Running the Example

```bash
python agent.py
```

### Example Interaction

```
User: "What is my GitHub user info?"

Agent: πŸ” GitHub authentication required. Please complete OAuth at: https://github.com/login/oauth/authorize?client_id=...

[User completes OAuth in browser]

Agent: βœ… GitHub authentication successful!
GitHub User Info:
Username: your-username
Name: Your Name
Email: your-email@example.com
Public Repos: 42
Followers: 10
Following: 25
```

## πŸ”§ Available Tools

The agent includes several GitHub tools:

- **`get_github_user_info`**: Get authenticated user's profile information
- **`get_github_repositories`**: List user's repositories with details
- **`get_github_followers`**: Get user's followers list
- **`get_weather`**: Simple weather tool (no authentication required)

## πŸ›‘οΈ Security Features

- **Secure Token Storage**: OAuth tokens are stored in runtime context, not persisted
- **Scoped Permissions**: Only requests necessary GitHub scopes (`repo`, `user`)
- **Automatic Cleanup**: Tokens are automatically cleaned up after session
- **Error Handling**: Graceful handling of authentication failures

## πŸ“š Key Concepts

### Middleware System
LangChain's middleware system allows you to intercept and modify agent behavior at different stages:
- `@before_model`: Before model invocation
- `@after_model`: After model invocation (used here)
- `@before_tool`: Before tool execution
- `@after_tool`: After tool execution

### Runtime Context
The `Context` dataclass provides a way to store and share data across the agent's execution:
- OAuth tokens
- User information
- Session state
- Custom metadata

### Interrupt System
LangGraph's interrupt system allows agents to pause execution and wait for external input:
- User authentication
- Manual approval
- External API responses
- Human-in-the-loop workflows

## πŸ”— Related Documentation

- [LangSmith Agent Auth Documentation](https://docs.langchain.com/langsmith/agent-auth)
- [LangChain Middleware Guide](https://docs.langchain.com/docs/agents/middleware)
- [LangGraph Interrupts](https://langchain-ai.github.io/langgraph/concepts/interrupts/)
- [GitHub OAuth Documentation](https://docs.github.com/en/developers/apps/building-oauth-apps)

## 🀝 Contributing

Feel free to submit issues and enhancement requests! This example demonstrates the core concepts, but there are many ways to extend it:

- Add more OAuth providers (Google, Microsoft, etc.)
- Implement token refresh logic
- Add user session management
- Create more sophisticated GitHub tools
- Add error recovery mechanisms

## πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.