{"id":50831384,"url":"https://github.com/langchain-samples/agent-oauth-example","last_synced_at":"2026-06-13T23:30:46.140Z","repository":{"id":360276831,"uuid":"1078184505","full_name":"langchain-samples/agent-oauth-example","owner":"langchain-samples","description":"This project demonstrates the new **Agent OAuth Authentication** capabilities in LangSmith, showcasing how to build intelligent agents that can securely authen…","archived":false,"fork":false,"pushed_at":"2025-10-17T10:57:13.000Z","size":156,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-25T19:37:32.296Z","etag":null,"topics":["authentication","intermediate","langgraph"],"latest_commit_sha":null,"homepage":null,"language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/langchain-samples.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-17T10:35:53.000Z","updated_at":"2026-03-04T18:26:37.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/langchain-samples/agent-oauth-example","commit_stats":null,"previous_names":["langchain-samples/agent-oauth-example"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/langchain-samples/agent-oauth-example","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/langchain-samples%2Fagent-oauth-example","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/langchain-samples%2Fagent-oauth-example/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/langchain-samples%2Fagent-oauth-example/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/langchain-samples%2Fagent-oauth-example/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/langchain-samples","download_url":"https://codeload.github.com/langchain-samples/agent-oauth-example/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/langchain-samples%2Fagent-oauth-example/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34304628,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-13T02:00:06.617Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication","intermediate","langgraph"],"created_at":"2026-06-13T23:30:45.391Z","updated_at":"2026-06-13T23:30:46.134Z","avatar_url":"https://github.com/langchain-samples.png","language":"Jupyter Notebook","funding_links":[],"categories":[],"sub_categories":[],"readme":"# LangSmith Agent OAuth Authentication Example\n\nThis 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.\n\n## 🚀 Features\n\n- **Seamless OAuth Integration**: Agents automatically handle OAuth flows when accessing protected resources\n- **Middleware-Based Authentication**: Uses LangChain's new middleware system to intercept tool calls and trigger authentication\n- **Interrupt-Driven Flow**: Agents pause execution to surface OAuth URLs to users, then resume after authentication\n- **Secure Token Management**: OAuth tokens are securely stored in runtime context and automatically used for API calls\n- **GitHub API Integration**: Example tools for accessing user info, repositories, and followers\n\n## 🏗️ Architecture\n\nThis example uses:\n- **LangChain v1** with `create_agent` for rapid agent development\n- **LangGraph middleware** (`@after_model`) to customize post-model behavior\n- **LangSmith OAuth** for secure authentication flows\n- **GitHub OAuth App** for external service integration\n\n## 🔄 OAuth Interrupt Flow\n\nWhen the agent needs to access GitHub data, it automatically pauses execution and shows the OAuth URL to the user:\n\n![Agent OAuth Interrupt Flow](assets/agent_oauth_interrupt.jpeg)\n\nThe 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.\n\n## 📋 Prerequisites\n\n1. **LangSmith Account**: Sign up at [langsmith.com](https://langsmith.com)\n2. **GitHub Account**: For creating OAuth applications\n3. **Python 3.8+**: For running the agent\n4. **Environment Variables**: API keys and configuration\n\n## 🛠️ Setup Instructions\n\n### Step 1: Create GitHub OAuth Application\n\n1. Go to [GitHub Settings \u003e Developer Settings \u003e OAuth Apps](https://github.com/settings/developers)\n2. Click \"New OAuth App\"\n3. Fill in the application details:\n   - **Application name**: `LangSmith Agent Auth Example`\n   - **Homepage URL**: `https://your-domain.com` (or `http://localhost:8000` for development)\n   - **Authorization callback URL**: `https://api.host.langchain.com/v2/auth/callback/agent-auth-github`\n4. Save the application and note down the **Client ID** and **Client Secret**\n\n### Step 2: Configure LangSmith OAuth Provider\n\n1. Go to [LangSmith Settings \u003e OAuth Providers](https://smith.langchain.com/settings/oauth-providers)\n2. Click \"Create OAuth Provider\"\n3. Configure the provider:\n   - **Provider ID**: `agent-auth-github`\n   - **Provider Name**: `GitHub`\n   - **Client ID**: (from GitHub OAuth App)\n   - **Client Secret**: (from GitHub OAuth App)\n   - **Authorization URL**: `https://github.com/login/oauth/authorize`\n   - **Token URL**: `https://github.com/login/oauth/access_token`\n   - **Scopes**: `repo,user`\n4. Save the provider configuration\n\n### Step 3: Install Dependencies\n\n```bash\npip install -r requirements.txt\n```\n\n### Step 4: Environment Configuration\n\nCreate a `.env` file with your API keys:\n\n```bash\n# LangSmith API Key (get from https://smith.langchain.com/settings)\nLANGSMITH_API_KEY=your_langsmith_api_key_here\n\n# OpenAI API Key (for the agent model)\nOPENAI_API_KEY=your_openai_api_key_here\n\n# Optional: LangSmith project for tracing\nLANGCHAIN_TRACING_V2=true\nLANGCHAIN_PROJECT=github-auth-example\n```\n\n## 🎯 How It Works\n\n### 1. Agent Creation with Middleware\n\nThe agent is created using LangChain's `create_agent` with custom middleware:\n\n```python\nfrom langchain.agents import create_agent\nfrom langchain.agents.middleware import after_model\n\n# Define context schema for runtime\n@dataclass\nclass Context:\n    github_token: str = None\n\n# Authentication middleware\n@after_model(can_jump_to=[\"end\"])\nasync def auth_github(state: AgentState, runtime: Runtime[Context]) -\u003e Dict[str, Any] | None:\n    # Check if GitHub tools are being called\n    # Trigger OAuth flow if needed\n    # Store token in runtime context\n\n# Create agent with middleware\nagent = create_agent(\n    model=\"openai:gpt-4o-mini\",\n    tools=[get_github_user_info, get_github_repositories, get_github_followers],\n    middleware=[auth_github],\n    context_schema=Context,\n)\n```\n\n### 2. OAuth Flow with Interrupts\n\nWhen the agent needs to access GitHub data:\n\n1. **Detection**: Middleware detects GitHub tool calls\n2. **Interrupt**: Agent pauses execution and shows OAuth URL\n3. **Authentication**: User completes OAuth flow in browser\n4. **Resume**: Agent continues with authenticated access\n\n```python\n# In the middleware\nif needs_auth and not runtime.context.github_token:\n    auth_result = await client.authenticate(\n        provider=\"agent-auth-github\",\n        scopes=[\"repo\", \"user\"],\n        user_id=\"user_123\",\n        agent_scoped=False\n    )\n    \n    if auth_result.needs_auth:\n        # Pause agent and show OAuth URL\n        interrupt(f\"🔐 GitHub authentication required. Please complete OAuth at: {auth_result.auth_url}\")\n    else:\n        # Store token for API calls\n        runtime.context.github_token = auth_result.token\n```\n\n### 3. Authenticated Tool Execution\n\nTools automatically use the stored OAuth token:\n\n```python\n@tool\nasync def get_github_user_info(runtime: ToolRuntime) -\u003e str:\n    headers = {\n        'Authorization': f'token {runtime.context.github_token}',\n        'Accept': 'application/vnd.github.v3+json'\n    }\n    # Make authenticated GitHub API calls\n```\n\n## 🚀 Running the Example\n\n```bash\npython agent.py\n```\n\n### Example Interaction\n\n```\nUser: \"What is my GitHub user info?\"\n\nAgent: 🔐 GitHub authentication required. Please complete OAuth at: https://github.com/login/oauth/authorize?client_id=...\n\n[User completes OAuth in browser]\n\nAgent: ✅ GitHub authentication successful!\nGitHub User Info:\nUsername: your-username\nName: Your Name\nEmail: your-email@example.com\nPublic Repos: 42\nFollowers: 10\nFollowing: 25\n```\n\n## 🔧 Available Tools\n\nThe agent includes several GitHub tools:\n\n- **`get_github_user_info`**: Get authenticated user's profile information\n- **`get_github_repositories`**: List user's repositories with details\n- **`get_github_followers`**: Get user's followers list\n- **`get_weather`**: Simple weather tool (no authentication required)\n\n## 🛡️ Security Features\n\n- **Secure Token Storage**: OAuth tokens are stored in runtime context, not persisted\n- **Scoped Permissions**: Only requests necessary GitHub scopes (`repo`, `user`)\n- **Automatic Cleanup**: Tokens are automatically cleaned up after session\n- **Error Handling**: Graceful handling of authentication failures\n\n## 📚 Key Concepts\n\n### Middleware System\nLangChain's middleware system allows you to intercept and modify agent behavior at different stages:\n- `@before_model`: Before model invocation\n- `@after_model`: After model invocation (used here)\n- `@before_tool`: Before tool execution\n- `@after_tool`: After tool execution\n\n### Runtime Context\nThe `Context` dataclass provides a way to store and share data across the agent's execution:\n- OAuth tokens\n- User information\n- Session state\n- Custom metadata\n\n### Interrupt System\nLangGraph's interrupt system allows agents to pause execution and wait for external input:\n- User authentication\n- Manual approval\n- External API responses\n- Human-in-the-loop workflows\n\n## 🔗 Related Documentation\n\n- [LangSmith Agent Auth Documentation](https://docs.langchain.com/langsmith/agent-auth)\n- [LangChain Middleware Guide](https://docs.langchain.com/docs/agents/middleware)\n- [LangGraph Interrupts](https://langchain-ai.github.io/langgraph/concepts/interrupts/)\n- [GitHub OAuth Documentation](https://docs.github.com/en/developers/apps/building-oauth-apps)\n\n## 🤝 Contributing\n\nFeel free to submit issues and enhancement requests! This example demonstrates the core concepts, but there are many ways to extend it:\n\n- Add more OAuth providers (Google, Microsoft, etc.)\n- Implement token refresh logic\n- Add user session management\n- Create more sophisticated GitHub tools\n- Add error recovery mechanisms\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flangchain-samples%2Fagent-oauth-example","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flangchain-samples%2Fagent-oauth-example","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flangchain-samples%2Fagent-oauth-example/lists"}