diff --git a/.ai_config_defaults.json b/.ai_config_defaults.json index 84c6310..210124d 100644 --- a/.ai_config_defaults.json +++ b/.ai_config_defaults.json @@ -9,7 +9,7 @@ "security-agent": { "enabled": true, "model": { - "name": "claude-haiku-4-5-20251001", + "name": "claude-haiku-5-5", "parameters": {} }, "provider": { @@ -20,7 +20,7 @@ "supervisor-agent": { "enabled": true, "model": { - "name": "claude-sonnet-4-6", + "name": "claude-haiku-5-5", "parameters": {} }, "provider": { @@ -31,7 +31,7 @@ "support-agent": { "enabled": true, "model": { - "name": "claude-haiku-4-5-20251001", + "name": "claude-haiku-5-5", "parameters": { "tools": [ { diff --git a/.env.example b/.env.example index 1641cb3..fd6436b 100644 --- a/.env.example +++ b/.env.example @@ -46,40 +46,14 @@ BEDROCK_EMBEDDING_DIMENSIONS=1024 # Options: 256, 512, 1024 BEDROCK_EMBEDDING_MODEL=amazon.titan-embed-text-v2:0 # Optional: MCP Tool Configuration -# These are used for advanced research capabilities (leave blank if not using MCP tools) +# Used for research capabilities in Part 2 (leave blank if not using MCP tools) +# OpenAlex needs no setting here: sign in once with `uv run python tools_impl/openalex_auth.py` ARXIV_MCP_SERVER_PATH=/Users/your_username/.local/bin/arxiv-mcp-server -SEMANTIC_SCHOLAR_SERVER_PATH=/tmp/semantic_scholar_server.py -# Optional: Database Configuration (if using database MCP tools) -# DATABASE_URL=postgresql://user:password@localhost:5432/your_database - -# Optional: GitHub Integration (if using GitHub MCP server) -# GITHUB_TOKEN=your_github_personal_access_token - -# Optional: Slack Integration (if using Slack MCP server) -# SLACK_BOT_TOKEN=xoxb-your-slack-bot-token -# SLACK_SIGNING_SECRET=your_slack_signing_secret - -# Application Configuration -# API Server Configuration +# API server the UI and traffic generators call API_HOST=localhost API_PORT=8000 -# Streamlit UI Configuration -UI_HOST=localhost -UI_PORT=8501 - -# Vector Store Configuration -VECTOR_STORE_PATH=data/vector_store/ -EMBEDDING_MODEL=amazon.titan-embed-text-v2:0 # Bedrock Titan V2 -# EMBEDDING_MODEL=text-embedding-3-small # Default: OpenAI (backward compatible) -CHUNK_SIZE=1000 -CHUNK_OVERLAP=200 - # Optional: Override embedding provider auto-detection # EMBEDDING_PROVIDER=bedrock # Force Bedrock embeddings -# EMBEDDING_PROVIDER=openai # Force OpenAI embeddings (requires OPENAI_API_KEY) - -# Development Mode -DEBUG=true -LOG_LEVEL=INFO \ No newline at end of file +# EMBEDDING_PROVIDER=openai # Force OpenAI embeddings (requires OPENAI_API_KEY) \ No newline at end of file diff --git a/.github/workflows/ai-config-validation.yml b/.github/workflows/ai-config-validation.yml index ba00693..0f0af49 100644 --- a/.github/workflows/ai-config-validation.yml +++ b/.github/workflows/ai-config-validation.yml @@ -54,12 +54,11 @@ jobs: - name: Install dependencies run: | - uv venv - # Install dependencies without installing the package itself (to avoid dev dependency issues) - uv pip install langchain langgraph langchain-anthropic fastapi "uvicorn[standard]" pydantic launchdarkly-server-sdk launchdarkly-server-sdk-ai numpy openai faiss-cpu PyMuPDF tiktoken streamlit requests python-dotenv PyYAML langchain-openai langchain-mcp-adapters beautifulsoup4 mcp semanticscholar rank-bm25 langchain-mistralai httpx boto3 langchain-aws - # Force fresh clone by clearing all caches - rm -rf ~/.cache/uv ~/.cache/pip /tmp/pip-* || true - uv pip install --no-cache --force-reinstall git+https://x-access-token:${{ secrets.GH_PAT }}@github.com/launchdarkly-labs/scarlett_ai_configs_ci_cd-.git@02cb9b1 + uv sync --frozen || uv sync + uv tool install --no-cache --with "launchdarkly-server-sdk-ai<0.11" git+https://x-access-token:${{ secrets.GH_PAT }}@github.com/launchdarkly-labs/scarlett_ai_configs_ci_cd-.git@02cb9b1 + + - name: Run unit tests + run: uv run pytest - name: Validate required secrets run: | @@ -80,7 +79,7 @@ jobs: LD_PROJECT_KEY: ${{ secrets.LD_PROJECT_KEY }} run: | # Use ld-aic-cicd framework to validate our AI configs - .venv/bin/ld-aic validate \ + ld-aic validate \ --environment ${{ github.event.inputs.environment || 'production' }} \ --config-keys "supervisor-agent,support-agent,security-agent" \ --report validation-report.json \ @@ -161,12 +160,8 @@ jobs: - name: Install dependencies run: | - uv venv - # Install dependencies without installing the package itself (to avoid dev dependency issues) - uv pip install langchain langgraph langchain-anthropic fastapi "uvicorn[standard]" pydantic launchdarkly-server-sdk launchdarkly-server-sdk-ai numpy openai faiss-cpu PyMuPDF tiktoken streamlit requests python-dotenv PyYAML langchain-openai langchain-mcp-adapters beautifulsoup4 mcp semanticscholar rank-bm25 langchain-mistralai httpx boto3 langchain-aws - # Force fresh clone by clearing all caches - rm -rf ~/.cache/uv ~/.cache/pip /tmp/pip-* || true - uv pip install --no-cache --force-reinstall git+https://x-access-token:${{ secrets.GH_PAT }}@github.com/launchdarkly-labs/scarlett_ai_configs_ci_cd-.git@02cb9b1 + uv sync --frozen || uv sync + uv tool install --no-cache --with "launchdarkly-server-sdk-ai<0.11" git+https://x-access-token:${{ secrets.GH_PAT }}@github.com/launchdarkly-labs/scarlett_ai_configs_ci_cd-.git@02cb9b1 - name: Validate required secrets run: | @@ -191,17 +186,11 @@ jobs: echo "πŸ“š Initializing vector embeddings for search tools..." .venv/bin/python initialize_embeddings.py - - name: Install MCP servers for research-enhanced variation + - name: Install MCP server for research-enhanced variation run: | - echo "πŸ“¦ Installing MCP servers (ArXiv and Semantic Scholar)..." - - # Install ArXiv MCP server + echo "πŸ“¦ Installing ArXiv MCP server..." uv tool install arxiv-mcp-server - - # Clone and set up Semantic Scholar MCP server - git clone https://github.com/JackKuo666/semanticscholar-MCP-Server.git - - echo "βœ… MCP servers installed (available for research-enhanced variation)" + echo "βœ… MCP server installed (available for research-enhanced variation)" - name: Start API server env: @@ -299,7 +288,7 @@ jobs: echo "🧹 Cleared old test artifacts to ensure fresh run" # Run tests with HTTP evaluator (calls API endpoint to test full system) - .venv/bin/ld-aic test \ + ld-aic test \ --config-keys "supervisor-agent,support-agent,security-agent" \ --environment production \ --evaluation-dataset test_data/ai_config_evaluation.yaml \ @@ -398,12 +387,8 @@ jobs: - name: Install dependencies run: | - uv venv - # Install dependencies without installing the package itself (to avoid dev dependency issues) - uv pip install langchain langgraph langchain-anthropic fastapi "uvicorn[standard]" pydantic launchdarkly-server-sdk launchdarkly-server-sdk-ai numpy openai faiss-cpu PyMuPDF tiktoken streamlit requests python-dotenv PyYAML langchain-openai langchain-mcp-adapters beautifulsoup4 mcp semanticscholar rank-bm25 langchain-mistralai httpx boto3 langchain-aws - # Force fresh clone by clearing all caches - rm -rf ~/.cache/uv ~/.cache/pip /tmp/pip-* || true - uv pip install --no-cache --force-reinstall git+https://x-access-token:${{ secrets.GH_PAT }}@github.com/launchdarkly-labs/scarlett_ai_configs_ci_cd-.git@02cb9b1 + uv sync --frozen || uv sync + uv tool install --no-cache --with "launchdarkly-server-sdk-ai<0.11" git+https://x-access-token:${{ secrets.GH_PAT }}@github.com/launchdarkly-labs/scarlett_ai_configs_ci_cd-.git@02cb9b1 - name: Validate required secrets run: | @@ -425,7 +410,7 @@ jobs: run: | echo "πŸ”„ Syncing AI configs from LaunchDarkly production..." mkdir -p configs - .venv/bin/ld-aic sync \ + ld-aic sync \ --environment production \ --output-dir configs \ --format json \ diff --git a/.gitignore b/.gitignore index b72dc25..f5efdc0 100644 --- a/.gitignore +++ b/.gitignore @@ -41,14 +41,12 @@ env/ ehthumbs.db Thumbs.db -# Tests -tests/ - # Documentation docs/ # Environment files .env +.openalex_tokens.json # Logs logs/ diff --git a/.python-version b/.python-version index 2c07333..e4fba21 100644 --- a/.python-version +++ b/.python-version @@ -1 +1 @@ -3.11 +3.12 diff --git a/.streamlit/config.toml b/.streamlit/config.toml new file mode 100644 index 0000000..b37f3ff --- /dev/null +++ b/.streamlit/config.toml @@ -0,0 +1,7 @@ +[theme] +base = "dark" +primaryColor = "#405BFF" +backgroundColor = "#191919" +secondaryBackgroundColor = "#232326" +textColor = "#F4F5F7" +font = "sans serif" diff --git a/AGENTS.md b/AGENTS.md index a39c9fc..86781a9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,10 +1,10 @@ # AGENTS.md -Companion code for the LaunchDarkly tutorial series *Chaos to Clarity: Defensible AI Systems*. A FastAPI service runs a LangGraph supervisor that routes to a security agent (PII detection) and a support agent (RAG over `kb/`), with every model, prompt, and tool selection delivered by LaunchDarkly AI Configs (AgentControl). The tutorials are the product; the code exists so a reader can follow them. +Companion code for the LaunchDarkly tutorial series *Chaos to Clarity: Defensible AI Systems*. A FastAPI service runs a LangGraph supervisor that routes to a security agent (PII detection) and a support agent (RAG over `kb/`), with every model, prompt, and tool selection delivered by LaunchDarkly AI configs. The tutorials are the product; the code exists so a reader can follow them. ## Setup and commands -- Python 3.11 via `uv`. `uv sync` installs runtime deps; `uv sync --group dev` adds pytest and ruff. +- Python 3.12 via `uv`. `uv sync` installs runtime deps; `uv sync --group dev` adds pytest and ruff. - `cp .env.example .env`. `LD_SDK_KEY` is always required. Choose one model auth path: `AUTH_METHOD=sso` (AWS Bedrock, needs `AWS_PROFILE` + `AWS_REGION`) or `AUTH_METHOD=api-key` (`ANTHROPIC_API_KEY`/`OPENAI_API_KEY`). `OPENAI_API_KEY` is also needed to rebuild embeddings. - API: `uv run uvicorn api.main:app --reload --port 8000`. Smoke check: `curl localhost:8000/health`, then POST `/chat`. - UI: `uv run streamlit run ui/chat_interface.py --server.port 8501`. @@ -14,13 +14,18 @@ Companion code for the LaunchDarkly tutorial series *Chaos to Clarity: Defensibl ## Verification -There is no unit-test suite in the repo (`tests/` is gitignored). Correctness is verified end to end: +Unit tests live in `tests/` and run offline without LaunchDarkly or LLM credentials: -1. API starts clean with your `.env` and `/health` returns 200. -2. A `/chat` request routes through supervisor β†’ security/support and the response names the served config variation. -3. CI (`.github/workflows/ai-config-validation.yml`) runs the `ld-aic-cicd` validator and LLM judge against the live LaunchDarkly project on every PR. It needs org secrets, so expect it to run on the PR, not locally. +- Unit tests: `uv run pytest` (covers fallback config loading, tracking attribution, Bedrock inference-profile resolution, security boundary isolation, tool-call caps, and bootstrap payloads). -Done means steps 1 and 2 pass locally for the tutorial part you changed. +End-to-end verification: + +1. `uv run pytest` passes. +2. API starts clean with your `.env` and `/health` returns 200. +3. A `/chat` request routes through supervisor β†’ security/support and the response names the served config variation. +4. CI (`.github/workflows/ai-config-validation.yml`) runs `uv run pytest` plus the `ld-aic-cicd` validator and LLM judge against the live LaunchDarkly project on every PR. The live judge steps need org secrets, so expect those to run on the PR rather than locally. + +Done means steps 1–3 pass locally for the tutorial part you changed. ## Names are contracts diff --git a/README.md b/README.md index 1036470..3c9b828 100644 --- a/README.md +++ b/README.md @@ -1,56 +1,27 @@ ---- -slug: /tutorials/agents-langgraph -title: "Build a LangGraph Multi-Agent system in 20 Minutes with LaunchDarkly AI Configs" -og:title: "Build a LangGraph Multi-Agent system in 20 Minutes with LaunchDarkly AI Configs" -description: Build a multi-agent system with dynamic configuration in 20 minutes using LangGraph multi-agent workflows, RAG search, and LaunchDarkly AI Configs. -og:description: Build a multi-agent system with dynamic configuration in 20 minutes using LangGraph multi-agent workflows, RAG search, and LaunchDarkly AI Configs. -keywords: tutorial, langgraph, multi-agent, AI configs, RAG, agents, python -publishedDate: 2025-09-08 -categories: - - AI ---- - -{/* cSpell:ignore devrel Barto rerank IPRL */} -

Published September 8th, 2025

-
- Portrait of Scarlett Attensil. -

by Scarlett Attensil

-
- - - -This tutorial was published in September 2025, before LaunchDarkly shipped several features that supersede or complement the patterns shown below. The walkthrough still works, but for new builds you'll likely want to use: +# Build a LangGraph multi-agent system in 20 minutes with LaunchDarkly AI configs -- [**Agent graphs**](/home/ai-configs/agent-graphs) β€” externalize the multi-agent topology into a visual graph with per-node monitoring (the newer take on this tutorial's pattern) -- [**Online evaluations**](/home/ai-configs/online-evaluations) and [**custom judges**](/home/ai-configs/custom-judges) β€” built-in and user-defined LLM-as-a-judge scoring on live traffic -- [**LLM Playground**](/home/ai-configs/playground) β€” compare variations side-by-side before promoting -- [**Offline evaluations + datasets**](/home/ai-configs/offline-evaluations) β€” regression-test variations against a saved reference set +> Read the full three-part series and companion tutorials on LaunchDarkly Docs: +> - **Part 1 (this branch)**: [Build a LangGraph multi-agent system in 20 minutes with LaunchDarkly AI configs](https://launchdarkly.com/docs/tutorials/agents-langgraph?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph) +> - **Part 2 (`tutorial_2.md`)**: [Target LangGraph agents and MCP tools with LaunchDarkly AI configs](https://launchdarkly.com/docs/tutorials/multi-agent-mcp-targeting?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph) +> - **Part 3 (`tutorial_3.md`)**: [Prove LangGraph agent ROI with LaunchDarkly A/B experiments](https://launchdarkly.com/docs/guides/experimentation/ai-experiments-roi?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph) +> - **Agent Graphs (`tutorial/agent-graphs` branch)**: [Beyond n8n for workflow automation: agent graphs as your universal agent harness](https://launchdarkly.com/docs/tutorials/agent-graphs?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph) +> - **Offline Evals (`feature/offline-evals` branch)**: [Evaluate RAG agent answers offline with LLM-as-a-judge in LaunchDarkly](https://launchdarkly.com/docs/tutorials/offline-evals?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph) -LaunchDarkly is also rebranding **AI Configs** as **AgentControl**. Slugs, SDK names, and APIs are unchanged. For the current reference, see [AgentControl documentation](/home/ai-configs). - - - -## Overview - -Build a working multi-agent system with dynamic configuration in 20 minutes using LangGraph multi-agent workflows, RAG search, and LaunchDarkly AI Configs. +Build a working multi-agent system with dynamic configuration in 20 minutes using LangGraph multi-agent workflows, RAG search, OpenTelemetry traces, and LaunchDarkly AI configs. *Part 1 of 3 of the series: **Chaos to Clarity: Defensible AI Systems That Deliver on Your Goals*** -You've been there: your AI chatbot works great in testing, then production hits and GPT-4 costs spiral out of control. You switch to Claude, but now European users need different privacy rules. Every change means another deploy, more testing, and crossed fingers that nothing breaks. +You've been there: your AI chatbot works great in testing, then production hits and frontier model costs spiral out of control. You switch to Claude, but now European users need different privacy rules. Every change means another deploy, more testing, and crossed fingers that nothing breaks. The teams shipping faster? They control AI behavior dynamically instead of hardcoding everything. -This series shows you how to build **LangGraph multi-agent workflows** that get their intelligence from **RAG** search through your business documents. These workflows are enhanced with **MCP tools** for live external data and controlled through **LaunchDarkly AI Configs**β€”all without needing to deploy code changes. +This series shows you how to build **LangGraph multi-agent workflows** that get their intelligence from **RAG** search through your business documents. These workflows are enhanced with **MCP tools** for live external data and controlled through **[LaunchDarkly Agent management](https://launchdarkly.com/docs/home/agentcontrol?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph)**, all without needing to deploy code changes. ## What This Series Covers -- **Part 1** (this post): Build a working multi-agent system with dynamic configuration in 20 minutes -- **Part 2**: Add advanced features like segment targeting, MCP tool integration, and cost optimization -- **Part 3**: Run production A/B experiments to prove what actually works +- **Part 1** (this guide): Build a working multi-agent system with dynamic configuration in 20 minutes +- **[Part 2](tutorial_2.md)**: Add segment targeting, MCP tool integration, and regional model routing ([LaunchDarkly Docs](https://launchdarkly.com/docs/tutorials/multi-agent-mcp-targeting?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph)) +- **[Part 3](tutorial_3.md)**: Run production A/B experiments to prove model and privacy ROI ([LaunchDarkly Docs](https://launchdarkly.com/docs/guides/experimentation/ai-experiments-roi?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph)) By the end, you'll have a system that measures its own performance and adapts based on user data instead of guesswork. @@ -67,8 +38,8 @@ In the next 20 minutes, you'll have a LangGraph multi-agent system with: You'll need: -- **Python 3.9+** with `uv` package manager ([install uv](https://docs.astral.sh/uv/getting-started/installation/)) -- **LaunchDarkly account** ([sign up for free](https://app.launchdarkly.com/signup)) +- **Python 3.12+** with `uv` package manager ([install uv](https://docs.astral.sh/uv/getting-started/installation/)) +- **LaunchDarkly account** ([sign up for free](https://app.launchdarkly.com/signup?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph)) **Choose your AI provider setup:** @@ -78,8 +49,8 @@ You'll need: - **Cost-effective** - enterprise-grade with cross-region failover **Option B: Direct API Keys (Traditional)** -- **OpenAI API key** (required for RAG architecture embeddings) -- **Anthropic API key** (for Claude models) or **OpenAI API key** (for GPT models) +- **OpenAI account & API key** ([sign up / create key at platform.openai.com/api-keys](https://platform.openai.com/api-keys)): required for RAG vector embeddings and Step 8's GPT model switch +- **Anthropic account & API key** ([sign up / create key at console.anthropic.com/settings/keys](https://console.anthropic.com/settings/keys)): required for the Claude agents in Step 5 ## Step 1: Clone and Configure (2 minutes) @@ -89,7 +60,6 @@ First, let's get everything running locally. We'll explain what each piece does # Get the code git clone https://github.com/launchdarkly-labs/devrel-agents-tutorial cd devrel-agents-tutorial -# Note: For the latest Agent Graphs implementation, use: git checkout tutorial/agent-graphs # Install dependencies (LangGraph, LaunchDarkly SDK, etc.) uv sync @@ -100,7 +70,7 @@ cp .env.example .env First, you need to get your LaunchDarkly SDK key by creating a project: -1. **Sign up for LaunchDarkly** at [app.launchdarkly.com](https://app.launchdarkly.com) (free account). +1. **Sign up for LaunchDarkly** at [app.launchdarkly.com](https://app.launchdarkly.com/signup?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph) (free account). If you're a brand new user, after signing up for an account, you'll need to verify your email address. You can skip through the new user onboarding flow after that. 2. **Find projects on the side bar:** @@ -118,7 +88,7 @@ First, you need to get your LaunchDarkly SDK key by creating a project: 🎯 **Use exact names for Part 2 compatibility**: - Project: `multi-agent-chatbot` -- AI Configs: `supervisor-agent`, `security-agent`, `support-agent` +- AI configs: `supervisor-agent`, `security-agent`, `support-agent` - Tools: `search_v2`, `reranking` - Variations: `supervisor-basic`, `pii-detector`, `rag-search-enhanced` @@ -155,6 +125,7 @@ Now configure your authentication method in `.env`: ```bash # LaunchDarkly Configuration LD_SDK_KEY=your-launchdarkly-sdk-key # From step above +LD_PROJECT_KEY=multi-agent-chatbot # Used for LaunchDarkly Trace & Monitoring deep links # AWS Bedrock Configuration AUTH_METHOD=sso # Use AWS SSO authentication @@ -183,6 +154,7 @@ aws bedrock list-foundation-models --region us-east-1 --profile your-sso-profile ```bash # LaunchDarkly Configuration LD_SDK_KEY=your-launchdarkly-sdk-key # From step above +LD_PROJECT_KEY=multi-agent-chatbot # Used for LaunchDarkly Trace & Monitoring deep links # Direct API Configuration AUTH_METHOD=api-key # Use direct API keys (default) @@ -209,24 +181,24 @@ aws sts get-caller-identity --profile your-sso-profile-name ### 🚨 **Bedrock Model ID Requirements:** -When configuring AI models in LaunchDarkly for Bedrock, you should use **inference profile IDs** (with region prefix): +With `AUTH_METHOD=sso`, every Claude model goes through Bedrock, which needs **inference profile IDs** (with region prefix). You can keep picking **Anthropic β†’ claude-haiku-5-5** in the steps below; the app converts it for you. -**βœ… BEST PRACTICE - Inference Profile IDs (with region prefix):** +**βœ… BEST PRACTICE - Inference Profile IDs (pick the Bedrock provider in LaunchDarkly):** ``` -us.anthropic.claude-sonnet-4-6-v2:0 -us.anthropic.claude-3-7-sonnet-20250219-v1:0 -eu.anthropic.claude-haiku-4-5-20251001-v2:0 +us.anthropic.claude-haiku-5-5 +eu.anthropic.claude-sonnet-5-5 +global.anthropic.claude-opus-5-5 ``` -**⚠️ AUTO-CORRECTED - Direct Model IDs (will be fixed automatically):** +**⚠️ AUTO-CORRECTED - Anthropic and direct Bedrock model IDs (will be fixed automatically):** ``` -anthropic.claude-3-7-sonnet-20250219-v1:0 β†’ us.anthropic.claude-3-7-sonnet-20250219-v1:0 -anthropic.claude-sonnet-4-6-v2:0 β†’ us.anthropic.claude-sonnet-4-6-v2:0 +claude-haiku-5-5 β†’ us.anthropic.claude-haiku-5-5 +anthropic.claude-sonnet-5-5 β†’ us.anthropic.claude-sonnet-5-5 ``` **How Auto-Correction Works:** -The system automatically converts direct model IDs to inference profile IDs to prevent `ValidationException` errors from Bedrock. The region prefix is determined by: +The system automatically converts Anthropic model names and direct model IDs to inference profile IDs to prevent `ValidationException` errors from Bedrock. The region prefix is determined by: 1. **`BEDROCK_INFERENCE_REGION`** env var (if set) - explicit user preference 2. **`AWS_REGION`** env var (e.g., `us-east-1` β†’ `us` prefix) - automatic detection @@ -247,7 +219,7 @@ aws bedrock list-inference-profiles --region us-east-1 --profile your-sso-profil **Why Inference Profiles?** -Bedrock requires inference profile IDs for on-demand throughput. The region prefix (`us.`, `eu.`, `ap.`, etc.) enables cross-region inference profiles for better availability and failover. +Bedrock requires inference profile IDs for on-demand throughput. The region prefix (`us.`, `eu.`, `global.`, etc.) enables cross-region inference profiles for better availability and failover. ## Step 2: Add Your Business Knowledge (2 minutes) @@ -285,20 +257,20 @@ This builds your **RAG** (Retrieval-Augmented Generation) foundation using **Ope Define the search tools your agents will use. -In the LaunchDarkly app sidebar, click **Library** in the AI section. On the following screen, click the **Tools** tab, then **Create tool**. +In the LaunchDarkly app sidebar, click **Agents**, then **Library**. On the following screen, click the **Tools** tab, then **Create tool**.
- + ![Library](screenshots/library_small.png)
### Create the RAG vector search tool: -Note: we will be creating a simple search_v1 during part 3 when we learn about experimentation. +Note: Part 2 creates a simple keyword search tool, search_v1, for free users. Create a tool using the following configuration: > > **Key:** @@ -375,27 +347,27 @@ The `reranking` tool takes search results from `search_v2` and reorders them usi ## Step 5: Create Your AI Agents in LaunchDarkly (5 minutes) -Now that you've created the tools your agents will use, it's time to configure the agents themselves. Each agent will have its own AI Config that defines its behavior, model selection, and specific instructions. +Now that you've created the tools your agents will use, it's time to configure the agents themselves. Each agent has its own AI config that defines its behavior, model selection, and specific instructions. -Create LaunchDarkly AI Configs to control your **LangGraph** multi-agent system dynamically. **LangGraph** is LangChain's framework for building stateful, multi-**agent** applications that maintain conversation state across **agent** interactions. Your **LangGraph** architecture enables sophisticated workflows where **agents** collaborate and pass context between each other. +Create LaunchDarkly AI configs to control your **LangGraph** multi-agent system dynamically. **LangGraph** is LangChain's framework for building stateful, multi-**agent** applications that maintain conversation state across **agent** interactions. Your **LangGraph** architecture enables sophisticated workflows where **agents** collaborate and pass context between each other. ### Create the Supervisor Agent -1. In the LaunchDarkly dashboard sidebar, navigate to **AI Configs** and click **Create AI Config** -2. Select `πŸ€– Agent-based` +1. In the LaunchDarkly sidebar, click **Agents**, then **Configs**, then **Create config** +2. Select **Agent**
- + ![Agent Based](screenshots/agent-based_small.png)
-3. Name your AI Config `supervisor-agent`. This will be the key you reference in your code. -4. Configure the following fields in the AI Config form: +3. Name your config `supervisor-agent`. This will be the key you reference in your code. +4. Configure the following fields in the config form: > > **variation:** @@ -408,7 +380,7 @@ Create LaunchDarkly AI Configs to control your **LangGraph** multi-agent system > Anthropic > ``` > ``` -> claude-sonnet-4-6 +> claude-haiku-5-5 > ``` > > **Goal or task:** @@ -437,7 +409,7 @@ Create LaunchDarkly AI Configs to control your **LangGraph** multi-agent system > Analyze this user input and recommend the optimal route: > ``` -Click **Review and save**. Now enable your AI Config by switching to the **Targeting** tab and editing the default rule to serve the variation you just created: +Click **Review and save**. Now enable your config by switching to the **Targeting** tab and editing the default rule to serve the variation you just created:
@@ -450,12 +422,12 @@ Click **Review and save**. Now enable your AI Config by switching to the **Targe Click **Edit** on the Default rule, change it to serve your `supervisor-basic` variation, and save with a note like "Enabling new agent config". Then type "Production" to confirm. -The supervisor **agent** demonstrates **LangGraph** orchestration by routing requests based on content analysis rather than rigid rules. **LangGraph** enables this **agent** to maintain conversation context and make intelligent routing decisions that adapt to user needs and LaunchDarkly AI Config parameters. +The supervisor **agent** demonstrates **LangGraph** orchestration by routing requests based on content analysis rather than rigid rules. **LangGraph** enables this **agent** to maintain conversation context and make intelligent routing decisions that adapt to user needs and AI config parameters. ### Create the Security Agent -Similarly, create another AI Config called `security-agent` +Similarly, create another config called `security-agent` > > **variation:** @@ -468,7 +440,7 @@ Similarly, create another AI Config called `security-agent` > Anthropic > ``` > ``` -> claude-sonnet-4-6 +> claude-haiku-5-5 > ``` > > **Goal or task:** @@ -495,7 +467,7 @@ Finally, create `support-agent` > Anthropic > ``` > ``` -> claude-sonnet-4-6 +> claude-haiku-5-5 > ``` > > β†’ **Add parameters** @@ -517,7 +489,7 @@ This **agent** combines **LangGraph** workflow management with your **RAG** tool **Remember to switch to the Targeting tab and enable this agent the same way - edit the default rule to serve your `rag-search-enhanced` variation and save it.** -When you are done, you should have three enabled AI Config Agents as shown below. +When you are done, you should have three enabled agent configs as shown below.
@@ -556,12 +528,17 @@ Test with these queries: Or ask about your specific domain: "What's our refund policy?" **PII Detection Test:** -"My email is john.doe@example.com and I need help" +Click **Security Check**, or paste: + +"My name is Jane Doe, email jane.doe@example.com. I work at Acme Corp in Berlin as a manager. Can you explain temporal-difference learning?" + +That message is two checks in one. The name and email are direct identifiers, so every variation redacts them. The employer, city, and job title are the borderline case: the default variation leaves them, and EU strict security redacts them. The banner under the answer shows the redacted text, so you can see which policy ran. **Basic Search** is the same kind of question with no personal details, and it should not be redacted. -**Workflow Details** show: -- Which agents are activated -- What models and tools are being used -- Text after redaction +Below every response, the observability bar shows: +- Which variation, model, and tools served your request +- An inline **PII redacted** banner whenever the security agent sanitized sensitive text +- **`β†— View Trace Waterfall`**: opens the exact OpenTelemetry trace in LaunchDarkly (`launchdarkly-ai-server[otel]` exports agent and tool spans automatically using your `LD_SDK_KEY`, with no extra keys or collector) +- **`β†— Monitoring & Metrics`**: opens `support-agent`'s Monitoring tab for token usage, latency, and error rates
@@ -581,15 +558,15 @@ Experience the power of dynamic configuration by making real-time changes to you ### Feature 1: Switch Models Instantly -1. Navigate to **AI Configs** in the LaunchDarkly sidebar +1. In the LaunchDarkly sidebar, click **Agents**, then **Configs** 2. Click on `support-agent` 3. In the **Model configuration** section, change from: - - **Current:** Anthropic β†’ claude-sonnet-4-6 - - **New:** OpenAI β†’ gpt-4-turbo + - **Current:** Anthropic β†’ claude-haiku-5-5 + - **New:** OpenAI β†’ gpt-6.1-terra 4. Click **Save changes** 5. Return to your chat interface at http://localhost:8501 -6. Ask the same question again - you'll see the response now comes from GPT-4 -7. **What you'll notice:** Different response style, potentially different tool usage patterns, and the model name displayed in the workflow details +6. Ask the same question again. You'll see the response now comes from GPT-6.1 Terra +7. **What you'll notice:** Different response style, potentially different tool usage patterns, and `gpt-6.1-terra` shown in the served bar and in the LaunchDarkly trace waterfall ### Feature 2: Adjust Tool Usage @@ -607,7 +584,7 @@ Limit how many times your agent can call tools in a single interaction: ``` 4. Click **Save changes** 5. In your chat, ask a complex question that would normally trigger multiple searches -6. **What you'll notice:** The agent now makes at most 2 tool calls, forcing it to be more selective about its searches +6. **What you'll notice:** The agent makes at most 2 tool calls. If it tries a third, the run stops and the reply starts with "I've reached the tool call limit for this request." The server logs show `TOOL CALL #1/2`, `TOOL CALL #2/2`, then `TOOL LIMIT REACHED` ### Feature 3: Change Agent Behavior @@ -661,7 +638,7 @@ Your multi-agent system is running with dynamic control and ready for optimizati 1. **Different Instructions**: Make agents more helpful, more cautious, or more thorough 2. **Tool Combinations**: Add/remove tools to see impact on quality -3. **Model Comparisons**: Try different models for different agents +3. **Model Comparisons**: Try different models for different agents. Keep the supervisor and security agents on a model that supports structured output, such as `claude-haiku-5-5`, a GPT model, or Mistral. Other Claude 5.5 models don't, so the security agent fails closed and every message reaches the support agent as `[Message withheld: the security check failed]` 4. **Cost Limits**: Find the sweet spot between quality and cost Every change is instant, measurable, and reversible. @@ -670,23 +647,25 @@ Every change is instant, measurable, and reversible. - Multi-agent systems work best when each agent has a specific role - Dynamic configuration handles changing requirements better than hardcoding -- LaunchDarkly AI Configs control and change AI behavior without requiring deployments +- LaunchDarkly AI configs control and change AI behavior without requiring deployments - Start simple and add complexity as you learn what works -Ready for more? [Continue to Part 2: Smart AI Agent Targeting with MCP Tools β†’](/tutorials/multi-agent-mcp-targeting) +Ready for more? [Continue to Part 2: Target LangGraph agents and MCP tools with LaunchDarkly AI configs β†’](https://launchdarkly.com/docs/tutorials/multi-agent-mcp-targeting?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph) ## Related Resources -Explore the **[LaunchDarkly MCP Server](/home/getting-started/mcp)** - enable AI agents to access feature flag configurations, user segments, and experimentation data directly through the Model Context Protocol. +Explore the **[LaunchDarkly MCP Server](https://launchdarkly.com/docs/home/getting-started/mcp?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph)** - enable AI agents to access feature flag configurations, user segments, AI configs, and experimentation data directly through the Model Context Protocol. **More from this series and related tutorials:** -- [Beyond n8n for Workflow Automation: Agent Graphs](/tutorials/agent-graphs) - The newer take on this pattern: externalize the topology itself into a visual graph with per-node monitoring -- [Building Framework-Agnostic AI Swarms](/tutorials/ai-orchestrators) - Compare LangGraph against Strands and OpenAI Swarm running the same agent definitions -- [Build AI Configs with Agent Skills](/tutorials/agent-skills-quickstart) - Generate the AI Configs in this tutorial from natural-language prompts -- [Offline Evaluation of RAG-Grounded Answers](/tutorials/offline-evals) - Add regression tests on the RAG outputs from this system -- [Proving ROI with data-driven AI agent experiments](/guides/experimentation/ai-experiments-roi) - Part 3: A/B test the variations you built here +- [Target LangGraph agents and MCP tools with LaunchDarkly AI configs](https://launchdarkly.com/docs/tutorials/multi-agent-mcp-targeting?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph) - Part 2: Add geo privacy routing, plan tiers, and live ArXiv and OpenAlex research tools +- [Prove LangGraph agent ROI with LaunchDarkly A/B experiments](https://launchdarkly.com/docs/guides/experimentation/ai-experiments-roi?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph) - Part 3: A/B test the variations you built here +- [Use LaunchDarkly Agent Skills in Claude Code and Cursor](https://launchdarkly.com/docs/tutorials/agent-skills-quickstart?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph) - Generate the AI configs in this tutorial from natural-language prompts +- [Benchmark LangGraph, Strands, OpenAI Agents, and Google ADK on the same agent graph](https://launchdarkly.com/docs/tutorials/agent-graph-experiments?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph) - Compare four orchestrators on latency and token usage over one LaunchDarkly agent graph +- [Beyond n8n for workflow automation: agent graphs as your universal agent harness](https://launchdarkly.com/docs/tutorials/agent-graphs?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph) - Externalize the topology itself into a visual graph with per-node monitoring +- [Evaluate RAG agent answers offline with LLM-as-a-judge in LaunchDarkly](https://launchdarkly.com/docs/tutorials/offline-evals?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph) - Add regression tests on the RAG outputs from this system +- [Run AgentControl offline evaluations in CI](https://launchdarkly.com/docs/tutorials/aic-cicd?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_agents-langgraph) - Gate every pull request on dataset evaluations in GitHub Actions --- -*Questions? Issues? Reach out at `aiproduct@launchdarkly.com` or open an issue in the [GitHub repo](https://github.com/launchdarkly-labs/devrel-agents-tutorial/tree/tutorial/agent-graphs).* +*Questions? Issues? Reach out at `aiproduct@launchdarkly.com` or open an issue in the [GitHub repo](https://github.com/launchdarkly-labs/devrel-agents-tutorial).* diff --git a/agents/ld_agent_helpers.py b/agents/ld_agent_helpers.py index cf6d939..ba79780 100644 --- a/agents/ld_agent_helpers.py +++ b/agents/ld_agent_helpers.py @@ -4,14 +4,15 @@ Creates agents with dynamic configuration from LaunchDarkly AI Configs. Routes between Bedrock (SSO) and direct API providers based on AUTH_METHOD. """ -import asyncio import time import os from typing import List, Any, Tuple from langchain.chat_models import init_chat_model -from langgraph.prebuilt import create_react_agent -from ldai.tracker import TokenUsage +from langchain_core.messages import HumanMessage +from langchain_core.tools import StructuredTool +from langgraph.prebuilt import ToolNode, create_react_agent from utils.logger import log_student +from utils.bedrock_helpers import ensure_bedrock_inference_profile from langchain_aws import ChatBedrockConverse import boto3 @@ -49,34 +50,19 @@ def create_bedrock_chat_model(model_id: str, session: boto3.Session, region: str Auto-corrects direct model IDs to inference profiles. Region from BEDROCK_INFERENCE_REGION env var or AWS_REGION. """ - try: - from utils.bedrock_helpers import ensure_bedrock_inference_profile + corrected_model_id = ensure_bedrock_inference_profile(model_id, region) - # Auto-correct to inference profile if needed - corrected_model_id = ensure_bedrock_inference_profile(model_id, region) + log_student(f"BEDROCK: Creating model {corrected_model_id} in region {region}") - log_student(f"BEDROCK: Creating model {corrected_model_id} in region {region}") - - # Create Bedrock client using the provided session - bedrock_client = session.client( - service_name='bedrock-runtime', - region_name=region - ) - - # Create the ChatBedrockConverse model - model = ChatBedrockConverse( - client=bedrock_client, - model_id=corrected_model_id, - region_name=region, - **kwargs - ) - - log_student(f"BEDROCK: Successfully created {corrected_model_id}") - return model + model = ChatBedrockConverse( + client=session.client(service_name='bedrock-runtime', region_name=region), + model_id=corrected_model_id, + region_name=region, + **kwargs + ) - except Exception as e: - log_student(f"BEDROCK ERROR: Failed to create model {model_id}: {e}") - raise + log_student(f"BEDROCK: Successfully created {corrected_model_id}") + return model def _rate_limit_llm_call(): """Simple rate limiter for LLM calls""" @@ -93,361 +79,251 @@ def _rate_limit_llm_call(): def map_provider_to_langchain(provider_name): - """Map LaunchDarkly provider names to LangChain provider names.""" - provider_mapping = { - 'anthropic': 'bedrock', # CHANGED: Route through Bedrock - 'bedrock': 'bedrock', # NEW: Explicit Bedrock provider - 'gemini': 'google_genai', - 'openai': 'openai', - 'mistral': 'mistralai' - } - lower_provider = provider_name.lower() - return provider_mapping.get(lower_provider, lower_provider) - - -def wrap_tool_with_counter(tool: Any, counter: ToolCallCounter) -> Any: - """ - Wrap a tool to track invocation count. + """Map LaunchDarkly provider names (e.g. 'Anthropic', 'bedrock:anthropic') to LangChain provider names.""" + provider = provider_name.lower() + if provider.startswith('bedrock:'): + return 'bedrock' + return {'gemini': 'google_genai', 'mistral': 'mistralai'}.get(provider, provider) - Each time the tool is called, the counter is incremented. - If max_tool_calls is exceeded, MaxToolCallsExceeded is raised. - Uses a closure-based approach to avoid pickling issues. +def create_chat_model(provider_name: str, model_name: str, config_manager, parameters: dict = None): """ - from langchain_core.tools import StructuredTool + Create the LangChain chat model for a LaunchDarkly AI Config. - # Store original methods - original_run = tool._run if hasattr(tool, '_run') else None - original_arun = tool._arun if hasattr(tool, '_arun') else None + Anthropic and Bedrock models go through Bedrock when AUTH_METHOD=sso, + otherwise through their direct API. Variation model parameters (excluding + attached tool schemas) are forwarded to the model constructor. + """ + provider = map_provider_to_langchain(provider_name) + model_params = {k: v for k, v in (parameters or {}).items() if k != "tools"} + + if provider in ('anthropic', 'bedrock') and os.getenv('AUTH_METHOD', 'api-key').lower() == 'sso': + return create_bedrock_chat_model( + model_id=model_name, + session=config_manager.boto3_session, + region=config_manager.aws_region, + **model_params, + ) - def counted_run(**kwargs) -> str: - """Wrapped synchronous execution""" - counter.increment() + # GPT-6 models accept function tools only on the Responses API + responses_api = {"use_responses_api": True} if provider == "openai" else {} + return init_chat_model(model=model_name, model_provider=provider, **responses_api, **model_params) - # Extract and log search query if present - query_info = "" - if 'query' in kwargs: - query_info = f" | Query: '{kwargs['query']}'" - elif 'search_query' in kwargs: - query_info = f" | Query: '{kwargs['search_query']}'" - log_student(f"TOOL CALL #{counter.count}/{counter.max_calls}: {tool.name}{query_info}") +def ci_safe_provider_and_model(provider_name: str, model_name: str) -> tuple[str, str]: + """Under CI_SAFE_MODE, use OpenAI when only an OpenAI key is available.""" + ci = os.getenv("CI_SAFE_MODE", "").lower() in {"1", "true", "yes"} + if ci and not os.getenv("ANTHROPIC_API_KEY") and os.getenv("OPENAI_API_KEY"): + return ("openai", "gpt-6-luna") + return (provider_name, model_name) - if original_run: - return original_run(**kwargs) - else: - raise NotImplementedError(f"Tool {tool.name} has no _run method") - async def counted_arun(**kwargs) -> str: - """Wrapped asynchronous execution""" - counter.increment() +def _tool_error_message(e: Exception) -> str: + """Tell the model a tool failed, but stop the run once the tool call limit is reached.""" + # ToolNode turns every tool exception into a message for the model by default, + # which would let the agent keep calling tools past max_tool_calls. + if isinstance(e, MaxToolCallsExceeded): + raise e + return f"Error: {e!r}\n Please fix your mistakes." + - # Extract and log search query if present - query_info = "" - if 'query' in kwargs: - query_info = f" | Query: '{kwargs['query']}'" - elif 'search_query' in kwargs: - query_info = f" | Query: '{kwargs['search_query']}'" +def wrap_tool_with_counter(tool: Any, counter: ToolCallCounter, tracked_fn: Any = None) -> Any: + """ + Wrap a tool to enforce max_tool_calls and delegate through the SDK's tracked handler. + Incrementing before delegating ensures a call past max_tool_calls raises + MaxToolCallsExceeded without recording an extra $ld:ai:tool_call event. + """ + def count_call(kwargs): + counter.increment() + query = kwargs.get('query') or kwargs.get('search_query') + query_info = f" | Query: '{query}'" if query else "" log_student(f"TOOL CALL #{counter.count}/{counter.max_calls}: {tool.name}{query_info}") - if original_arun: - return await original_arun(**kwargs) - elif original_run: - return original_run(**kwargs) - else: - raise NotImplementedError(f"Tool {tool.name} has no run method") + def counted_run(**kwargs) -> str: + count_call(kwargs) + return tool._run(**kwargs) + + async def counted_arun(**kwargs) -> str: + count_call(kwargs) + if tracked_fn is not None: + return await tracked_fn(**kwargs) + return await tool._arun(**kwargs) - # Create new StructuredTool with wrapped methods return StructuredTool( name=tool.name, description=tool.description, func=counted_run, - coroutine=counted_arun if original_arun or original_run else None, - args_schema=tool.args_schema if hasattr(tool, 'args_schema') else None + coroutine=counted_arun, + args_schema=tool.args_schema ) +def _to_async_tool_handler(tool: Any): + async def call_tool(**kwargs) -> str: + return await tool._arun(**kwargs) + return call_tool + + +def _extract_turn_output(messages: List[Any]) -> Tuple[str, List[str], List[dict]]: + """Extract assistant response text and tool-call summaries from new turn messages.""" + ai_response = "" + tool_calls_summary = [] + tool_details = [] + + for msg in messages: + if msg.type != 'ai': + continue + + if isinstance(msg.content, list): + for content_item in msg.content: + if isinstance(content_item, dict) and content_item.get('type') == 'text': + ai_response += content_item.get('text', '') + " " + elif msg.content: + ai_response += str(msg.content) + " " + + for tool_call in msg.tool_calls: + args = tool_call.get('args') or {} + detail = {"name": tool_call['name'], "args": args} + search_query = args.get('query') or args.get('search_query') + if search_query: + detail["search_query"] = search_query + tool_calls_summary.append(tool_call['name']) + tool_details.append(detail) + + final_text = ai_response.strip() or "I understand your question. Let me help you with that." + return final_text, tool_calls_summary, tool_details + + +def _build_react_agent(config_manager, agent_config, tools: List[Any], tracked_tools: dict = None, variables: dict = None) -> Tuple[Any, int]: + """Build the LangGraph ReAct agent from a resolved ServedConfig and SDK-wrapped tools.""" + llm = create_chat_model(agent_config.provider_name, agent_config.model_name, config_manager, agent_config.parameters) + log_student(f"ROUTING: Using {agent_config.provider_name} for {agent_config.model_name}") + + max_tool_calls = 5 + if 'max_tool_calls' in agent_config.custom: + max_tool_calls = int(agent_config.custom['max_tool_calls']) + log_student(f"EXTRACTED max_tool_calls from LaunchDarkly: {max_tool_calls}") + + counter = ToolCallCounter(max_calls=max_tool_calls) + tracked_map = tracked_tools or {} + wrapped_tools = [wrap_tool_with_counter(tool, counter, tracked_map.get(tool.name)) for tool in tools] + + effective_recursion_limit = max_tool_calls * 3 + 10 + log_student(f"CONFIG: max_tool_calls={max_tool_calls}, effective_recursion_limit={effective_recursion_limit}") + + agent = create_react_agent( + model=llm, + tools=ToolNode(wrapped_tools, handle_tool_errors=_tool_error_message), + prompt=agent_config.render_instructions(variables), + ) + return agent, effective_recursion_limit + + async def create_agent_with_fresh_config( config_manager, config_key: str, user_id: str, user_context: dict, - tools: List[Any] = None -) -> Tuple[Any, Any, bool, int]: + tools: List[Any] +) -> Tuple[Any, Any, int]: """ Create LangChain agent with LaunchDarkly AI Config. Routes to Bedrock (AUTH_METHOD=sso) or direct API based on config. - Returns: (agent, tracker, disabled, max_tool_calls) + Returns: (agent, served_config, recursion_limit) """ - if tools is None: - tools = [] - - try: - # Fetch config from LaunchDarkly - agent_config = await config_manager.get_config( - user_id=user_id, - config_key=config_key, - user_context=user_context - ) - - if not agent_config.enabled: - default_recursion_limit = 5 * 3 + 10 # Default: 5 tool calls * 3 + headroom - return None, None, True, default_recursion_limit - - # Map provider and create LangChain model - from utils.bedrock_helpers import normalize_bedrock_provider - - # Normalize provider name to handle bedrock:anthropic format - normalized_provider = normalize_bedrock_provider(agent_config.provider.name) - langchain_provider = map_provider_to_langchain(normalized_provider) - - # Check if we need to use Bedrock - if langchain_provider == 'bedrock': - # Get AUTH_METHOD to determine routing - auth_method = os.getenv('AUTH_METHOD', 'api-key').lower() - - if auth_method == 'sso': - # Use Bedrock with SSO authentication - if not hasattr(config_manager, 'boto3_session') or not config_manager.boto3_session: - raise ValueError("Bedrock authentication requires AWS SSO session. Run: aws sso login") - - # Use model ID directly from LaunchDarkly AI Config (FR-006 compliance) - bedrock_model_id = agent_config.model.name - - # 🚨 DEBUG: Log what we received from LaunchDarkly - log_student("DEBUG: LaunchDarkly AI Config details:") - log_student(f" - Provider: {agent_config.provider.name}") - log_student(f" - Model ID: {bedrock_model_id}") - log_student(f" - Region: {config_manager.aws_region}") - - # Create Bedrock model using our factory - llm = create_bedrock_chat_model( - model_id=bedrock_model_id, - session=config_manager.boto3_session, - region=config_manager.aws_region - ) - log_student(f"ROUTING: Using Bedrock SSO with direct model ID: {bedrock_model_id}") - else: - # Fall back to direct API access for backward compatibility - # Route 'anthropic' through 'anthropic' provider directly when using api-key auth - fallback_provider = 'anthropic' if agent_config.provider.name.lower() == 'anthropic' else langchain_provider - llm = init_chat_model( - model=agent_config.model.name, - model_provider=fallback_provider, - ) - log_student(f"ROUTING: Using direct API for {agent_config.model.name} via {fallback_provider}") - else: - # Use standard LangChain initialization for non-Bedrock providers - llm = init_chat_model( - model=agent_config.model.name, - model_provider=langchain_provider, - ) - log_student(f"ROUTING: Using {langchain_provider} for {agent_config.model.name}") - - # Extract max_tool_calls from LaunchDarkly config - max_tool_calls = 5 # Default value - try: - config_dict = agent_config.to_dict() - if 'model' in config_dict and 'custom' in config_dict['model'] and config_dict['model']['custom']: - custom_params = config_dict['model']['custom'] - if 'max_tool_calls' in custom_params: - max_tool_calls = int(custom_params['max_tool_calls']) - log_student(f"EXTRACTED max_tool_calls from LaunchDarkly: {max_tool_calls}") - except Exception as e: - log_student(f"DEBUG: Error extracting max_tool_calls: {e}") - - # Wrap tools with call counter to track invocations - counter = ToolCallCounter(max_calls=max_tool_calls) - wrapped_tools = [wrap_tool_with_counter(tool, counter) for tool in tools] - - # Calculate effective recursion limit - # Formula: max_tool_calls * 3 + 10 headroom - # Each tool call cycle: think β†’ tool_call β†’ tool_result β†’ think - effective_recursion_limit = max_tool_calls * 3 + 10 - log_student(f"CONFIG: max_tool_calls={max_tool_calls}, effective_recursion_limit={effective_recursion_limit}") - - # Create React agent with wrapped tools - agent = create_react_agent( - model=llm, - tools=wrapped_tools, - prompt=agent_config.instructions - ) - - return agent, agent_config.create_tracker(), False, effective_recursion_limit - - except Exception as e: - log_student(f"ERROR in create_agent_with_fresh_config: {e}") - default_recursion_limit = 5 * 3 + 10 # Default: 5 tool calls * 3 + headroom - return None, None, True, default_recursion_limit + agent_config = await config_manager.get_config( + user_id=user_id, + config_key=config_key, + user_context=user_context + ) + agent, effective_recursion_limit = _build_react_agent(config_manager, agent_config, tools) + return agent, agent_config, effective_recursion_limit -def create_simple_agent_wrapper(config_manager, config_key: str, tools: List[Any] = None): +def create_simple_agent_wrapper(config_manager, config_key: str, tools: List[Any], served_config=None): """ - Create agent wrapper that fetches fresh LaunchDarkly config on each invocation. + Create agent wrapper that runs inside LaunchDarkly's execute_and_track. - Enables dynamic A/B testing and real-time config changes without restarts. - Tracks tokens, costs, and errors automatically. + Reuses `served_config` when already resolved for the turn (avoiding duplicate + flag evaluations), or fetches a fresh config per call when standalone. """ - if tools is None: - tools = [] + tool_handlers = {tool.name: _to_async_tool_handler(tool) for tool in tools} class LaunchDarklyAgent: async def ainvoke(self, request_data: dict) -> dict: """ - Async invocation - fetches config and executes without blocking event loop + Async invocation - executes and records duration, tokens, tool calls, and output. """ + user_input = request_data.get("user_input", "") try: - # Extract request parameters - user_input = request_data.get("user_input", "") user_id = request_data.get("user_id", "agent_user") user_context = request_data.get("user_context", {}) - messages = request_data.get("messages", []) + agent_messages = request_data.get("messages") or [HumanMessage(content=user_input)] - # Create agent with config - agent, tracker, disabled, effective_recursion_limit = await create_agent_with_fresh_config( - config_manager=config_manager, - config_key=config_key, + served = served_config or await config_manager.get_config( user_id=user_id, - user_context=user_context, - tools=tools + config_key=config_key, + user_context=user_context ) - if disabled: - log_student(f"{config_key}: AI Config is disabled") - return { - "user_input": user_input, - "response": f"AI Config {config_key} is disabled", - "tool_calls": [], - "tool_details": [], - "messages": [] - } - - # Prepare messages for agent - if messages: - agent_messages = messages - else: - from langchain_core.messages import HumanMessage - agent_messages = [HumanMessage(content=user_input)] - - # Build state initial_state = {"messages": agent_messages} prev_message_count = len(agent_messages) - - # Get agent configuration for tracking - agent_config = await config_manager.get_config( - user_id=user_id, - config_key=config_key, - user_context=user_context - ) + ld_context = config_manager.build_context(user_id, user_context) # Apply rate limiting before LLM call _rate_limit_llm_call() - # Execute agent with tracking - start_time = time.time() - try: - # Execute agent with effective recursion limit + async def run_agent(tracked_tools=None, variables=None): + agent, effective_recursion_limit = _build_react_agent( + config_manager, served, tools, tracked_tools, variables + ) log_student(f"EXECUTING AGENT with recursion_limit={effective_recursion_limit}") - response = await agent.ainvoke(initial_state, {"recursion_limit": effective_recursion_limit}) - - # Track success and latency - tracker.track_success() - latency_ms = int((time.time() - start_time) * 1000) - tracker.track_duration(latency_ms) - - # Extract token usage from new messages - new_messages = response['messages'][prev_message_count:] - total_input = 0 - total_output = 0 - + try: + result = await agent.ainvoke(initial_state, {"recursion_limit": effective_recursion_limit}) + except MaxToolCallsExceeded as exc: + # Returned, not raised: reaching the tool limit is expected and isn't a generation error. + limit_msg = f"I've reached the tool call limit for this request. {exc}" + return exc, limit_msg, {} + + new_messages = result['messages'][prev_message_count:] + usage = {"input_tokens": 0, "output_tokens": 0} for msg in new_messages: - if hasattr(msg, 'usage_metadata') and msg.usage_metadata: - total_input += msg.usage_metadata.get('input_tokens', 0) - total_output += msg.usage_metadata.get('output_tokens', 0) - - # Track tokens if found - if total_input > 0 or total_output > 0: - token_usage = TokenUsage( - input=total_input, - output=total_output, - total=total_input + total_output - ) - tracker.track_tokens(token_usage) - log_student(f"AGENT TOKENS: {token_usage.total} tokens ({token_usage.input} in, {token_usage.output} out)") - - # Track cost metric with AI Config metadata for experiment attribution - from utils.cost_calculator import calculate_cost - cost = calculate_cost(agent_config.model.name, total_input, total_output) - if cost > 0: - # Use centralized context builder to ensure exact match with AI Config evaluation - ld_context = config_manager.build_context(user_id, user_context) - - # Track cost with metadata for experiment attribution - config_manager.track_cost_metric(agent_config, ld_context, cost, config_key) - log_student(f"COST TRACKING: ${cost:.6f} for {agent_config.model.name}") - - except MaxToolCallsExceeded as e: - # Handle tool limit gracefully - this is expected behavior, not an error - log_student(f"TOOL LIMIT REACHED: {e}") - # Return friendly message explaining the limit + if getattr(msg, 'usage_metadata', None): + usage["input_tokens"] += msg.usage_metadata.get('input_tokens', 0) + usage["output_tokens"] += msg.usage_metadata.get('output_tokens', 0) + + final_text, tool_calls_summary, tool_details = _extract_turn_output(new_messages) + turn_payload = (final_text, tool_calls_summary, tool_details, result['messages']) + return turn_payload, final_text, usage + + response = await config_manager.track( + served, + ld_context, + run_agent, + user_input, + tool_handlers=tool_handlers, + capture_content=True, # support-agent only sees redacted, PII-free text + ) + + if isinstance(response, MaxToolCallsExceeded): + log_student(f"TOOL LIMIT REACHED: {response}") return { "user_input": user_input, - "response": f"I've reached the tool call limit for this request. {str(e)}", + "response": f"I've reached the tool call limit for this request. {response}", "tool_calls": [], "tool_details": [], "messages": [] } - except Exception: - tracker.track_error() - raise - - # Extract new messages - new_messages = response['messages'][prev_message_count:] - - # Parse response - ai_response = "" - tool_calls_summary = [] - tool_details = [] - - for msg in new_messages: - # Get AI message content - if hasattr(msg, 'content') and msg.content: - if isinstance(msg.content, list): - for content_item in msg.content: - if hasattr(content_item, 'text'): - ai_response += content_item.text + " " - else: - ai_response += str(msg.content) + " " - - # Track tool calls - if hasattr(msg, 'tool_calls') and msg.tool_calls: - for tool_call in msg.tool_calls: - if hasattr(tool_call, 'name'): - tool_name = tool_call.name - tool_calls_summary.append(tool_name) - - # Try to extract details with search query - if hasattr(tool_call, 'args'): - detail = { - "name": tool_name, - "args": tool_call.args - } - # Extract search query from args if present - if isinstance(tool_call.args, dict): - if 'query' in tool_call.args: - detail["search_query"] = tool_call.args['query'] - elif 'search_query' in tool_call.args: - detail["search_query"] = tool_call.args['search_query'] - tool_details.append(detail) + final_text, tool_calls_summary, tool_details, all_messages = response return { "user_input": user_input, - "response": ai_response.strip() if ai_response else "I understand your question. Let me help you with that.", + "response": final_text, "tool_calls": tool_calls_summary, "tool_details": tool_details, - "messages": response['messages'] + "messages": all_messages } except Exception as e: @@ -462,30 +338,4 @@ async def ainvoke(self, request_data: dict) -> dict: "messages": [] } - def invoke(self, request_data: dict) -> dict: - """ - Synchronous invocation - runs async code in new event loop - """ - try: - # Try to run in existing event loop first - try: - asyncio.get_running_loop() - # We're in an async context, create task - import concurrent.futures - with concurrent.futures.ThreadPoolExecutor() as executor: - future = executor.submit(asyncio.run, self.ainvoke(request_data)) - return future.result() - except RuntimeError: - # No event loop, create one - return asyncio.run(self.ainvoke(request_data)) - except Exception as e: - log_student(f"SYNC INVOKE ERROR in {config_key}: {e}") - return { - "user_input": request_data.get("user_input", ""), - "response": f"I apologize, but I encountered an error: {e}", - "tool_calls": [], - "tool_details": [], - "messages": [] - } - - return LaunchDarklyAgent() \ No newline at end of file + return LaunchDarklyAgent() diff --git a/agents/security_agent.py b/agents/security_agent.py index 0579069..67ae67d 100644 --- a/agents/security_agent.py +++ b/agents/security_agent.py @@ -1,15 +1,17 @@ from typing import TypedDict, List, Annotated from langgraph.graph import StateGraph, add_messages from langchain_core.messages import AIMessage, BaseMessage, SystemMessage -from langchain.chat_models import init_chat_model from config_manager import FixedConfigManager as ConfigManager from pydantic import BaseModel from utils.logger import log_student +from .ld_agent_helpers import create_chat_model, ci_safe_provider_and_model, _rate_limit_llm_call + +WITHHELD_MESSAGE = "[Message withheld: the security check failed]" class PIIDetectionResponse(BaseModel): """Structured response for PII detection results""" detected: bool - types: List[str] + types: List[str] redacted: str class AgentState(TypedDict): @@ -61,14 +63,7 @@ def create_security_agent(agent_config, config_manager: ConfigManager): - Returns structured results (detected, types, redacted) - No external tools required for PII detection """ - - # Clear cache to ensure latest config - config_manager.clear_cache() - - # NOTE: Model will be created at runtime with fresh LaunchDarkly config - - - # NOTE: Instructions are fetched on each call using LaunchDarkly pattern + # NOTE: Model and instructions are fetched on each call from LaunchDarkly async def call_model(state: AgentState): """ @@ -91,210 +86,84 @@ async def call_model(state: AgentState): try: messages = state["messages"] - # Fetch config dynamically for each call - # Get latest config from LaunchDarkly user_context = state.get("user_context", {}) user_id = state.get("user_id", "security_user") - agent_config = await config_manager.get_config( + served = agent_config or await config_manager.get_config( user_id=user_id, config_key="security-agent", user_context=user_context ) - if not agent_config.enabled: - # Return safe default if config is disabled - return { - "messages": [AIMessage(content="PII Analysis: detected=false, types=[]")], - "detected": False, - "types": [], - "redacted": state["messages"][0].content if state["messages"] else "", - "response": "Security check disabled" - } - - # Create tracker for token, cost, and success/error metrics - tracker = agent_config.create_tracker() - # Create model with structured output and up-to-date instructions - from agents.ld_agent_helpers import map_provider_to_langchain, create_bedrock_chat_model - from utils.bedrock_helpers import normalize_bedrock_provider - import os - - # CI_SAFE_MODE: Prefer OpenAI when Anthropic unavailable - def _select_provider_and_model(default_provider: str, default_model: str) -> tuple[str, str]: - ci = os.getenv("CI_SAFE_MODE", "").lower() in {"1", "true", "yes"} - anthropic_key = os.getenv("ANTHROPIC_API_KEY") - openai_key = os.getenv("OPENAI_API_KEY") - if ci and (not anthropic_key) and openai_key: - return ("openai", "gpt-4o-mini") - return (default_provider, default_model) - - selected_provider, selected_model = _select_provider_and_model( - agent_config.provider.name, - agent_config.model.name - ) - - # Normalize provider name to handle bedrock:anthropic format - normalized_provider = normalize_bedrock_provider(selected_provider) - langchain_provider = map_provider_to_langchain(normalized_provider) - - # Check if we need to use Bedrock routing - if langchain_provider == 'bedrock': - # Get AUTH_METHOD to determine routing - auth_method = os.getenv('AUTH_METHOD', 'api-key').lower() - - if auth_method == 'sso': - # Use Bedrock with SSO authentication - if not hasattr(config_manager, 'boto3_session') or not config_manager.boto3_session: - raise ValueError("Bedrock authentication requires AWS SSO session. Run: aws sso login") - - # Use model ID directly from LaunchDarkly AI Config (FR-006 compliance) - bedrock_model_id = selected_model - - # 🚨 DEBUG: Log what we received from LaunchDarkly - log_student("DEBUG SECURITY: LaunchDarkly AI Config details:") - log_student(f" - Provider: {agent_config.provider.name}") - log_student(f" - Model ID: {bedrock_model_id}") - log_student(f" - Region: {config_manager.aws_region}") - - # Create Bedrock model using our factory - base_model = create_bedrock_chat_model( - model_id=bedrock_model_id, - session=config_manager.boto3_session, - region=config_manager.aws_region, - temperature=0.0 - ) - log_student(f"SECURITY ROUTING: Using Bedrock SSO with direct model ID: {bedrock_model_id}") - else: - # Fall back to direct API access for backward compatibility - # Route 'anthropic' through 'anthropic' provider directly when using api-key auth - fallback_provider = 'anthropic' if selected_provider.lower() == 'anthropic' else langchain_provider - base_model = init_chat_model( - model=selected_model, - model_provider=fallback_provider, - temperature=0.0 - ) - log_student(f"SECURITY ROUTING: Using direct API for {selected_model} via {fallback_provider}") - else: - # Use standard LangChain initialization for non-Bedrock providers - base_model = init_chat_model( - model=selected_model, - model_provider=langchain_provider, - temperature=0.0 - ) - log_student(f"SECURITY ROUTING: Using {langchain_provider} for {selected_model}") + provider, model = ci_safe_provider_and_model(served.provider_name, served.model_name) + base_model = create_chat_model(provider, model, config_manager, served.parameters) + log_student(f"SECURITY ROUTING: Using {provider} for {model}") # Use structured output for guaranteed PII format - # include_raw=True preserves usage metadata for cost tracking + # include_raw=True keeps the usage metadata that token and cost tracking need structured_model = base_model.with_structured_output(PIIDetectionResponse, include_raw=True) - # Create system message with current instructions from LaunchDarkly - system_message = SystemMessage(content=agent_config.instructions) - full_messages = [system_message] + messages - # Apply rate limiting before LLM call - from agents.ld_agent_helpers import _rate_limit_llm_call _rate_limit_llm_call() - # Call model with structured output - if hasattr(structured_model, "ainvoke"): - response = await structured_model.ainvoke(full_messages) - else: - response = structured_model.invoke(full_messages) - - # Extract parsed result from response - pii_result = response["parsed"] if isinstance(response, dict) else response - - # Extract and track token usage from raw response - if isinstance(response, dict) and "raw" in response and hasattr(response["raw"], "usage_metadata"): - usage_data = response["raw"].usage_metadata - if usage_data: - from ldai.tracker import TokenUsage - token_usage = TokenUsage( - input=usage_data.get("input_tokens", 0), - output=usage_data.get("output_tokens", 0), - total=usage_data.get("total_tokens", 0) - ) - tracker.track_tokens(token_usage) - log_student(f"SECURITY PII DETECTION TOKENS: {token_usage.total} tokens ({token_usage.input} in, {token_usage.output} out)") - - # Track cost metric with AI Config metadata for experiment attribution - from utils.cost_calculator import calculate_cost - cost = calculate_cost(agent_config.model.name, token_usage.input, token_usage.output) - if cost > 0: - # Use centralized context builder to ensure exact match with AI Config evaluation - user_id = state.get("user_id", "security_user") - user_context_data = state.get("user_context", {}) - ld_context = config_manager.build_context(user_id, user_context_data) - - # Track cost with metadata for experiment attribution - config_manager.track_cost_metric(agent_config, ld_context, cost, "security-agent") - log_student(f"COST TRACKING: ${cost:.6f} for {agent_config.model.name}") - - # Track success metric - tracker.track_success() - - # Extract structured results - detected = pii_result.detected - types = pii_result.types - redacted_text = pii_result.redacted + async def run_security(_tools=None, variables=None): + system_message = SystemMessage(content=served.render_instructions(variables)) + response = await structured_model.ainvoke([system_message] + messages) + if response["parsed"] is None: + raise ValueError(f"{model} returned no structured PII result; use a model that supports structured output") + parsed = response["parsed"] + return parsed, parsed.model_dump_json(), response["raw"].usage_metadata + + ld_context = config_manager.build_context(user_id, user_context) + pii_result = await config_manager.track(served, ld_context, run_security, state.get("user_input")) # Store structured results in state and create AI message for conversation flow - response_message = AIMessage(content=f"PII Analysis: detected={detected}, types={types}") + summary = f"PII Analysis: detected={pii_result.detected}, types={pii_result.types}" return { - "messages": [response_message], - "detected": detected, - "types": types, - "redacted": redacted_text, - "response": f"PII Analysis: detected={detected}, types={types}" + "messages": [AIMessage(content=summary)], + "detected": pii_result.detected, + "types": pii_result.types, + "redacted": pii_result.redacted, + "response": summary } - - except Exception: - - # Track error with LDAI metrics - try: - if 'agent_config' in locals() and agent_config: - agent_config.create_tracker().track_error() - except Exception: - pass - + + except Exception as e: + log_student(f"SECURITY ERROR: {e}") + + # Fail closed: an unchecked message may contain PII, so it never reaches the support agent. error_response = AIMessage(content="Security processing encountered an error.") return { "messages": [error_response], "detected": False, "types": [], - "redacted": state.get("user_input", "") + "redacted": WITHHELD_MESSAGE } - - + + def format_final_response(state: AgentState): """Format the final security agent response""" messages = state["messages"] - + # Get final response from last AI message - final_message = None - for message in reversed(messages): - if isinstance(message, AIMessage) and message.content: - final_message = message - break - - if final_message: - final_response = final_message.content - else: - final_response = "Security processing completed." - + final_response = next( + (m.content for m in reversed(messages) if isinstance(m, AIMessage) and m.content), + "Security processing completed." + ) + # Get PII results from state (set directly by call_model with structured output) pii_detected = state.get("detected", False) pii_types = state.get("types", []) - redacted_text = state.get("redacted", state.get("user_input", "")) - + # An empty redaction must not fall back to the raw input, which may contain PII + redacted_text = state.get("redacted") or WITHHELD_MESSAGE + if pii_detected: pii_summary = f"Found {', '.join(pii_types)}" if pii_types else "Sensitive data detected" log_student(f"SECURITY: {pii_summary} β†’ Sanitized") else: log_student("SECURITY: Clean - No PII detected") - + return { "user_input": state["user_input"], "response": final_response, @@ -303,10 +172,10 @@ def format_final_response(state: AgentState): "messages": messages, # Return the exact PII schema fields for supervisor and UI "detected": pii_detected, - "types": pii_types, + "types": pii_types, "redacted": redacted_text } - + # ============================================= # LANGGRAPH WORKFLOW CONSTRUCTION # ============================================= @@ -323,6 +192,4 @@ def format_final_response(state: AgentState): workflow.add_edge("call_model", "format") # Always go to formatting workflow.set_finish_point("format") # End with formatted results - # Note: No conditional routing needed - security agent has simple linear flow - - return workflow.compile() \ No newline at end of file + return workflow.compile() diff --git a/agents/supervisor_agent.py b/agents/supervisor_agent.py index cd71bec..6a8ebdf 100644 --- a/agents/supervisor_agent.py +++ b/agents/supervisor_agent.py @@ -2,7 +2,8 @@ from langgraph.graph import StateGraph, add_messages from langchain_core.messages import HumanMessage, AIMessage, BaseMessage, SystemMessage from .support_agent import create_support_agent -from .security_agent import create_security_agent +from .security_agent import create_security_agent, WITHHELD_MESSAGE +from .ld_agent_helpers import create_chat_model, ci_safe_provider_and_model, _rate_limit_llm_call from config_manager import FixedConfigManager as ConfigManager from utils.logger import log_student, log_debug from pydantic import BaseModel @@ -29,13 +30,12 @@ def trim_message_history(messages: List[BaseMessage], max_messages: int = 10) -> log_student(f"MEMORY MANAGEMENT: Trimmed all {len(conversation_messages)} conversation messages, keeping only {len(system_messages)} system messages") return system_messages - # Keep the most recent messages, ensuring we end with assistant response if possible + # Keep the most recent messages recent_messages = conversation_messages[-max_messages:] # Log that we're trimming for educational purposes trimmed_count = len(conversation_messages) - len(recent_messages) - if trimmed_count > 0: - log_student(f"MEMORY MANAGEMENT: Trimmed {trimmed_count} old messages, keeping {len(recent_messages)} recent + {len(system_messages)} system messages") + log_student(f"MEMORY MANAGEMENT: Trimmed {trimmed_count} old messages, keeping {len(recent_messages)} recent + {len(system_messages)} system messages") return system_messages + recent_messages @@ -98,7 +98,7 @@ def create_supervisor_agent(supervisor_config, support_config, security_config, β–Ό β–Ό β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ SUPPORT AGENT β”‚ β”‚ SUPPORT AGENT β”‚ -β”‚ β”‚. β”‚ β”‚ +β”‚ β”‚ β”‚ β”‚ β”‚ Direct Route β”‚ β”‚ Post-Security β”‚ β”‚ (No PII) β”‚ β”‚ (Sanitized) β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ @@ -116,35 +116,13 @@ def create_supervisor_agent(supervisor_config, support_config, security_config, - Security boundaries through state field management - Dynamic configuration via LaunchDarkly integration """ - - # Import needed modules for model creation - from langchain.chat_models import init_chat_model - # Create child agents with config manager support_agent = create_support_agent(support_config, config_manager) security_agent = create_security_agent(security_config, config_manager) - # Create tracker for the supervisor's own LLM calls and orchestration metrics - supervisor_tracker = supervisor_config.create_tracker() - log_debug(f"SUPERVISOR INSTRUCTIONS: {supervisor_config.instructions}") - def _select_provider_and_model(default_provider: str, default_model: str) -> tuple[str, str]: - """Select provider/model for CI while preserving full functionality. - - If CI_SAFE_MODE is set and Anthropic is unavailable but OpenAI is available, - prefer OpenAI to avoid external connectivity issues while still exercising LLMs. - """ - import os - ci = os.getenv("CI_SAFE_MODE", "").lower() in {"1", "true", "yes"} - anthropic_key = os.getenv("ANTHROPIC_API_KEY") - openai_key = os.getenv("OPENAI_API_KEY") - - if ci and (not anthropic_key) and openai_key: - return ("openai", "gpt-4o-mini") - return (default_provider, default_model) - - def pii_prescreen_node(state: SupervisorState): + async def pii_prescreen_node(state: SupervisorState): """ Analyze user input to determine if it likely contains PII. Routes to security agent if PII suspected, otherwise direct to support. @@ -155,92 +133,29 @@ def pii_prescreen_node(state: SupervisorState): user_context = state.get("user_context", {}) # Create PII pre-screening model with structured output - from agents.ld_agent_helpers import map_provider_to_langchain, create_bedrock_chat_model - from utils.bedrock_helpers import normalize_bedrock_provider - import os - - # CI_SAFE_MODE: Prefer OpenAI when Anthropic unavailable - selected_provider, selected_model = _select_provider_and_model( - supervisor_config.provider.name, - supervisor_config.model.name - ) - - # Normalize provider name to handle bedrock:anthropic format - normalized_provider = normalize_bedrock_provider(selected_provider) - langchain_provider = map_provider_to_langchain(normalized_provider) - - # Handle Bedrock vs direct API routing - if langchain_provider == 'bedrock': - auth_method = os.getenv('AUTH_METHOD', 'api-key').lower() - if auth_method == 'sso' and hasattr(config_manager, 'boto3_session') and config_manager.boto3_session: - base_model = create_bedrock_chat_model( - model_id=selected_model, - session=config_manager.boto3_session, - region=config_manager.aws_region, - temperature=0.1 - ) - else: - # Fall back to direct anthropic API - fallback_provider = 'anthropic' if selected_provider.lower() == 'anthropic' else langchain_provider - base_model = init_chat_model( - model=selected_model, - model_provider=fallback_provider, - temperature=0.1 - ) - else: - base_model = init_chat_model( - model=selected_model, - model_provider=langchain_provider, - temperature=0.1 - ) + provider, model = ci_safe_provider_and_model(supervisor_config.provider_name, supervisor_config.model_name) + base_model = create_chat_model(provider, model, config_manager, supervisor_config.parameters) - # Use include_raw=True to preserve usage metadata for cost tracking + # include_raw=True keeps the usage metadata that token and cost tracking need prescreen_model = base_model.with_structured_output(PIIPreScreening, include_raw=True) - # Get pre-screening prompt from LaunchDarkly config - prescreen_prompt = supervisor_config.instructions - - screening_message = HumanMessage(content=f"{prescreen_prompt}\n\nUser Input: {user_input}") - # Apply rate limiting before LLM call - from agents.ld_agent_helpers import _rate_limit_llm_call _rate_limit_llm_call() - # Get structured pre-screening result with raw response - response = prescreen_model.invoke([screening_message]) - screening_result = response["parsed"] if isinstance(response, dict) else response - - # Extract and track token usage from raw response - if isinstance(response, dict) and "raw" in response and hasattr(response["raw"], "usage_metadata"): - usage_data = response["raw"].usage_metadata - if usage_data: - from ldai.tracker import TokenUsage - token_usage = TokenUsage( - input=usage_data.get("input_tokens", 0), - output=usage_data.get("output_tokens", 0), - total=usage_data.get("total_tokens", 0) - ) - supervisor_tracker.track_tokens(token_usage) - log_student(f"PII PRESCREEN TOKENS: {token_usage.total} tokens ({token_usage.input} in, {token_usage.output} out)") - - # Track cost metric with AI Config metadata for experiment attribution - from utils.cost_calculator import calculate_cost - cost = calculate_cost(supervisor_config.model.name, token_usage.input, token_usage.output) - if cost > 0: - # Use centralized context builder to ensure exact match with AI Config evaluation - user_id = state.get("user_id", "supervisor_user") - user_context = state.get("user_context", {}) - ld_context = config_manager.build_context(user_id, user_context) - - # Track cost with metadata for experiment attribution - config_manager.track_cost_metric(supervisor_config, ld_context, cost, "supervisor-agent") - log_student(f"COST TRACKING: ${cost:.6f} for {supervisor_config.model.name}") - - # Track success metric - supervisor_tracker.track_success() - - # Log the intelligent decision - log_student(f"ROUTING: {screening_result.recommended_route} ({screening_result.confidence:.1f}) - {screening_result.reasoning}") + async def call_prescreen(_tools=None, variables=None): + prescreen_prompt = supervisor_config.render_instructions(variables) + screening_message = HumanMessage(content=f"{prescreen_prompt}\n\nUser Input: {user_input}") + response = await prescreen_model.ainvoke([screening_message]) + if response["parsed"] is None: + raise ValueError(f"{model} returned no structured routing decision; use a model that supports structured output") + parsed = response["parsed"] + return parsed, parsed.recommended_route, response["raw"].usage_metadata + + ld_context = config_manager.build_context(user_id, user_context) + screening_result = await config_manager.track(supervisor_config, ld_context, call_prescreen, user_input) + + # The reasoning can quote the PII, so only the route and confidence are logged + log_student(f"ROUTING: {screening_result.recommended_route} ({screening_result.confidence:.1f})") # Update workflow stage based on decision if screening_result.recommended_route == "security_agent": @@ -251,13 +166,13 @@ def pii_prescreen_node(state: SupervisorState): return { "current_agent": screening_result.recommended_route, "workflow_stage": next_stage, - "messages": [AIMessage(content=f"Routing decision: {screening_result.reasoning}")] + # The reasoning can quote the PII, so only the route goes into the conversation + "messages": [AIMessage(content=f"Routing decision: {screening_result.recommended_route}")] } except Exception as e: # Fallback to security agent for safety log_student(f"PII PRE-SCREENING ERROR: {type(e).__name__}: {str(e)}") - log_debug(f"PII PRE-SCREENING ERROR DETAIL: {e}") log_student("FALLBACK: Defaulting to security agent for safety") return { "current_agent": "security_agent", @@ -282,37 +197,26 @@ def supervisor_node(state: SupervisorState): - Central orchestration node that doesn't do LLM processing - Uses state fields to make routing decisions - Returns minimal state updates (just routing info) - - Tracks metrics for LaunchDarkly optimization """ - try: - workflow_stage = state.get("workflow_stage", "pii_prescreen") # Start with intelligent pre-screening - security_cleared = state.get("security_cleared", False) - support_response = state.get("support_response", "") - - # Track supervisor decision-making process - # Enhanced routing logic with intelligent pre-screening - if workflow_stage == "pii_prescreen": - next_agent = "pii_prescreen" - elif workflow_stage == "security_processing" and not security_cleared: - next_agent = "security_agent" - elif workflow_stage == "direct_support" and not support_response: - next_agent = "support_agent" - log_student("BYPASS: Direct to support (no PII detected)") - elif workflow_stage == "post_security_support" and not support_response: - next_agent = "support_agent" - log_student("SECURED: Routing to support with sanitized data") - elif support_response: - next_agent = "complete" - else: - # All workflow stages should be handled above - default to complete - next_agent = "complete" - # Track successful supervisor decision - return {"current_agent": next_agent} - - except Exception: + workflow_stage = state.get("workflow_stage", "pii_prescreen") # Start with intelligent pre-screening + security_cleared = state.get("security_cleared", False) + support_response = state.get("support_response", "") + + if workflow_stage == "pii_prescreen": + next_agent = "pii_prescreen" + elif workflow_stage == "security_processing" and not security_cleared: + next_agent = "security_agent" + elif workflow_stage == "direct_support" and not support_response: + next_agent = "support_agent" + log_student("BYPASS: Direct to support (no PII detected)") + elif workflow_stage == "post_security_support" and not support_response: + next_agent = "support_agent" + log_student("SECURED: Routing to support with sanitized data") + else: + # Support has answered, or an agent failed: format what we have + next_agent = "complete" + return {"current_agent": next_agent} - # Track supervisor error with LDAI metrics - return {"current_agent": "security_agent"} async def security_node(state: SupervisorState): """ LANGGRAPH NODE: Security Agent Orchestration @@ -322,8 +226,7 @@ async def security_node(state: SupervisorState): SECURITY ISOLATION WORKFLOW: 1. Prepare security agent input with raw user data 2. Execute security agent to detect and redact PII - 3. Create sanitized message history for support agent - 4. Update state with security results and sanitized data + 3. Update state with security results and the redacted text CRITICAL PII BOUNDARY: - Input: Raw user data (may contain PII) @@ -336,8 +239,6 @@ async def security_node(state: SupervisorState): - Implements security boundaries through state field management """ try: - - # Track supervisor orchestration start for security agent # Prepare security agent input security_input = { "user_input": state["user_input"], @@ -347,58 +248,36 @@ async def security_node(state: SupervisorState): "tool_calls": [], "messages": [HumanMessage(content=state["messages"][-2].content if len(state["messages"]) >= 2 else state["user_input"])] } - - # Execute security agent - if hasattr(security_agent, "ainvoke"): - result = await security_agent.ainvoke(security_input) - else: - result = security_agent.invoke(security_input) - - # Track successful supervisor orchestration for security agent - # After security processing, route to support with sanitized data - new_stage = "post_security_support" + + result = await security_agent.ainvoke(security_input) # Extract PII schema fields from security agent detected = result.get("detected", False) types = result.get("types", []) - redacted_text = result.get("redacted", state["user_input"]) - - # Create sanitized message history - replace original user input with redacted version - sanitized_messages = [] - original_messages = state.get("messages", []) - - for msg in original_messages: - if isinstance(msg, HumanMessage): - sanitized_msg = HumanMessage(content=redacted_text) - sanitized_messages.append(sanitized_msg) - else: - sanitized_messages.append(msg) - - # Add the security agent's response + # An empty redaction must not fall back to the raw input, which may contain PII + redacted_text = result.get("redacted") or WITHHELD_MESSAGE + security_response = AIMessage(content=result["response"]) - sanitized_messages.append(security_response) - - + + # sanitized_messages keeps the earlier, already redacted turns; the support node adds this one return { "messages": [security_response], # Only add security response to main message flow - "workflow_stage": new_stage, + "workflow_stage": "post_security_support", # Route to support with sanitized data "security_cleared": True, # Always proceed after security agent "processed_user_input": redacted_text, # Use redacted text for support agent "pii_detected": detected, "pii_types": types, "redacted_text": redacted_text, - "sanitized_messages": sanitized_messages, # Store clean message history - "security_tool_details": result.get("tool_details", []) # Capture security agent tool details } - - except Exception as e: - # Track error with LDAI metrics - supervisor_tracker.track_error() + except Exception as e: + # The failed agent already recorded its own generation error. return { "messages": [AIMessage(content=f"Security agent error: {e}")], "workflow_stage": "error", - "security_cleared": False + "security_cleared": False, + # The UI saves redacted_text as history, so never leave the raw input there + "redacted_text": WITHHELD_MESSAGE, } async def support_node(state: SupervisorState): @@ -415,7 +294,7 @@ async def support_node(state: SupervisorState): CRITICAL SECURITY BOUNDARY ENFORCEMENT: - Support agent NEVER sees raw user input containing PII - - All message history is pre-sanitized by security agent + - Message history only holds earlier turns that were already redacted - Support agent operates in completely PII-isolated environment LANGGRAPH PATTERNS: @@ -423,95 +302,53 @@ async def support_node(state: SupervisorState): - Orchestrates child agent with controlled input - Manages tool execution and result aggregation """ - try: - - # Track supervisor orchestration start for support agent - # Use processed (potentially redacted) text if available - processed_input = state.get("processed_user_input", state["user_input"]) - - # Safety check: Ensure processed input is not empty - if not processed_input or not processed_input.strip(): - processed_input = state["user_input"] # Fallback to original input - - pii_detected = state.get("pii_detected", False) - pii_types = state.get("pii_types", []) - sanitized_messages = state.get("sanitized_messages", []) - - # ===== CRITICAL SECURITY BOUNDARY: PII ISOLATION ===== - # Support agent must NEVER see raw messages containing PII - # Only sanitized/redacted messages are passed through this boundary - if sanitized_messages: - # Include conversation history + current redacted message - full_messages = sanitized_messages + [HumanMessage(content=processed_input)] - else: - full_messages = [HumanMessage(content=processed_input)] # Fallback to redacted current message only - - # === MESSAGE MEMORY MANAGEMENT === - # Trim message history to prevent context window overflow - # This is critical for long conversations that could exceed model limits - support_messages = trim_message_history(full_messages, max_messages=10) - - # Safety check: Ensure all messages have non-empty content - valid_messages = [] - for msg in support_messages: - if hasattr(msg, 'content') and msg.content and msg.content.strip(): - valid_messages.append(msg) - - # Ensure we have at least one valid message - if not valid_messages: - valid_messages = [HumanMessage(content=processed_input)] - - support_messages = valid_messages - - # ===== SUPPORT AGENT COMPLETE PII ISOLATION ===== - # This input contains ONLY sanitized/redacted content - # Support agent operates in completely PII-free environment - - # Log PII protection status - if pii_detected: - log_student(f"PII PROTECTED: {', '.join(pii_types)} redacted") - - support_input = { - "user_input": processed_input, # Redacted text only - "user_id": state.get("user_id", "support_user"), # For LaunchDarkly context - "user_context": state.get("user_context", {}), # For LaunchDarkly targeting - "response": "", - "tool_calls": [], - "tool_details": [], - "messages": support_messages # Sanitized conversation history only - } - - # Execute support agent - if hasattr(support_agent, "ainvoke"): - result = await support_agent.ainvoke(support_input) - else: - result = support_agent.invoke(support_input) - - # Track successful supervisor orchestration for support agent - tool_calls = result.get("tool_calls", []) - support_response = result["response"] - - tool_details = result.get('tool_details', []) + # Use the redacted text if the security agent ran; the original input only on the direct route + if state.get("security_cleared"): + processed_input = state.get("processed_user_input") or WITHHELD_MESSAGE + else: + processed_input = state["user_input"] + + pii_detected = state.get("pii_detected", False) + pii_types = state.get("pii_types", []) + + # ===== CRITICAL SECURITY BOUNDARY: PII ISOLATION ===== + # Support agent must NEVER see raw messages containing PII + # Only sanitized/redacted messages are passed through this boundary + full_messages = state.get("sanitized_messages", []) + [HumanMessage(content=processed_input)] + + # === MESSAGE MEMORY MANAGEMENT === + # Trim message history to prevent context window overflow + # This is critical for long conversations that could exceed model limits + support_messages = trim_message_history(full_messages, max_messages=10) + + # Models reject messages with empty content + support_messages = [msg for msg in support_messages if msg.content and msg.content.strip()] + if not support_messages: + support_messages = [HumanMessage(content=processed_input)] + + if pii_detected: + log_student(f"PII PROTECTED: {', '.join(pii_types)} redacted") + + support_input = { + "user_input": processed_input, # Redacted text only + "user_id": state.get("user_id", "support_user"), # For LaunchDarkly context + "user_context": state.get("user_context", {}), # For LaunchDarkly targeting + "response": "", + "tool_calls": [], + "tool_details": [], + "messages": support_messages # Sanitized conversation history only + } - return { - "messages": [AIMessage(content=support_response)], - "support_response": support_response, - "support_tool_calls": tool_calls, - "support_tool_details": tool_details, - "workflow_stage": "complete" - } - - except Exception as e: - # Track error with LDAI metrics - supervisor_tracker.track_error() + # The support agent returns a friendly error response instead of raising + result = await support_agent.ainvoke(support_input) - return { - "messages": [AIMessage(content=f"Support agent error: {e}")], - "support_response": f"Error processing request: {e}", - "support_tool_calls": [], - "support_tool_details": [], - "workflow_stage": "error" - } + return { + "messages": [AIMessage(content=result["response"])], + "support_response": result["response"], + "support_tool_calls": result.get("tool_calls", []), + "support_tool_details": result.get("tool_details", []), + "workflow_stage": "complete" + } def route_decision(state: SupervisorState) -> Literal["pii_prescreen", "security_agent", "support_agent", "complete"]: """ @@ -541,41 +378,15 @@ def route_decision(state: SupervisorState) -> Literal["pii_prescreen", "security return "support_agent" else: return "complete" - + def format_final(state: SupervisorState): - """Format final response with supervisor completion metrics""" - try: - - # Track supervisor workflow completion - support_tool_calls = state.get("support_tool_calls", []) - support_response = state.get("support_response", "") - - if support_response: - final_content = support_response - else: - final_message = state["messages"][-1] - final_content = final_message.content - - - return { - "final_response": final_content, - "actual_tool_calls": support_tool_calls, - "support_tool_details": state.get("support_tool_details", []), - "user_input": state["user_input"], - "workflow_stage": "complete" - } - - except Exception as e: - - # Track supervisor final formatting error - return { - "final_response": f"I apologize, but I encountered an error finalizing the response: {e}", - "actual_tool_calls": [], - "support_tool_details": [], - "user_input": state["user_input"], - "workflow_stage": "error" - } - + """Use the support agent's answer, or the last message if an agent failed""" + final_content = state.get("support_response") or state["messages"][-1].content + return { + "final_response": final_content, + "workflow_stage": "complete" + } + # ============================================= # LANGGRAPH WORKFLOW CONSTRUCTION # ============================================= @@ -617,5 +428,5 @@ def format_final(state: SupervisorState): # === SET FINISH POINT === # Workflow ends at format_final node workflow.set_finish_point("format_final") - - return workflow.compile() \ No newline at end of file + + return workflow.compile() diff --git a/agents/support_agent.py b/agents/support_agent.py index 0cb522d..a29d68b 100644 --- a/agents/support_agent.py +++ b/agents/support_agent.py @@ -11,10 +11,8 @@ Instead of hardcoded tools, this agent's capabilities are entirely controlled by LaunchDarkly configuration, enabling A/B testing of tool availability. """ -from typing import List, Any from .ld_agent_helpers import create_simple_agent_wrapper from tools_impl.dynamic_tool_factory import create_dynamic_tools_from_launchdarkly -from utils.logger import log_student def create_support_agent(config, config_manager): @@ -23,13 +21,13 @@ def create_support_agent(config, config_manager): LANGGRAPH INTEGRATION PATTERN: This function returns an agent wrapper that integrates with LangGraph - by exposing an invoke() method that matches LangGraph node expectations. + by exposing an ainvoke() method that the supervisor's support node awaits. DYNAMIC TOOL LOADING WORKFLOW: 1. Extract tool definitions from LaunchDarkly AI Config 2. Create actual tool instances using dynamic factory 3. Create agent wrapper that fetches fresh config on each call - 4. Return wrapper with invoke() method for LangGraph compatibility + 4. Return wrapper with ainvoke() method for LangGraph compatibility - Tools are NOT hardcoded - they come from LaunchDarkly configuration - Different users can get different tool sets based on targeting rules @@ -37,9 +35,9 @@ def create_support_agent(config, config_manager): - Agent wrapper pattern enables runtime configuration changes LAUNCHDARKLY TOOL VARIATIONS: - - docs-only: ["search_v1"] - Basic search only - - rag-enabled: ["search_v1", "search_v2", "reranking"] - Full RAG stack - - research-enhanced: ["search_v1", "search_v2", "reranking", "arxiv_search"] - RAG + MCP + - rag-search-enhanced (Part 1): ["search_v2", "reranking"] - RAG stack + - eu-free, other-free (Part 2): ["search_v1"] - Basic search only + - eu-paid, other-paid (Part 2): ["search_v1", "search_v2", "reranking", "arxiv_search", "openalex_search"] - RAG + MCP """ # STEP 1: Extract tool definitions from LaunchDarkly AI Config @@ -53,9 +51,9 @@ def create_support_agent(config, config_manager): agent_wrapper = create_simple_agent_wrapper( config_manager=config_manager, config_key="support-agent", # LaunchDarkly AI Config key - tools=available_tools # Tools loaded from configuration + tools=available_tools, # Tools loaded from configuration + served_config=config, # Reuse the config already evaluated for this turn ) - # STEP 3: Return wrapper with invoke() method for LangGraph integration - # The wrapper's invoke() method matches LangGraph node function signature - return agent_wrapper \ No newline at end of file + # STEP 3: Return wrapper with ainvoke() method for LangGraph integration + return agent_wrapper diff --git a/api/main.py b/api/main.py index ff3c4f4..0cafb22 100644 --- a/api/main.py +++ b/api/main.py @@ -1,5 +1,5 @@ +from contextlib import asynccontextmanager from fastapi import FastAPI -import os from dotenv import load_dotenv from .models import ChatRequest, ChatResponse, FeedbackRequest, FeedbackResponse @@ -9,10 +9,17 @@ load_dotenv() -app = FastAPI() - agent_service = AgentService() + +@asynccontextmanager +async def lifespan(_app: FastAPI): + yield + await agent_service.config_manager.aclose() + + +app = FastAPI(lifespan=lifespan) + @app.get("/health") async def health(): """Health check endpoint for monitoring""" @@ -24,13 +31,12 @@ async def chat(request: ChatRequest): with capture_console_output() as console_logs: message_text = request.message or "" log_student(f"API: Processing request from {request.user_id}") - log_debug(f"API: Message: '{message_text[:50]}{'...' if len(message_text) > 50 else ''}', Context: {request.user_context}") - + # The raw message may contain PII, so only its length is logged + log_debug(f"API: Message: {len(message_text)} chars, Context: {request.user_context}") + # Server-side guard against empty/whitespace messages if not message_text.strip(): - log_debug(" API: Empty message - returning validation response") - from .models import ChatResponse as CR - validation_response = CR( + return ChatResponse( id="validation", response="Please enter a question or pick an example query.", tool_calls=[], @@ -39,104 +45,57 @@ async def chat(request: ChatRequest): agent_configurations=[], console_logs=console_logs ) - return validation_response - try: - # SECURITY BOUNDARY: Pass sanitized conversation history only - # Raw messages with PII are never sent to support agent - strict isolation maintained - result = await agent_service.process_message( - user_id=request.user_id, - message=request.message, # Raw message (security agent processes this) - user_context=request.user_context, - sanitized_conversation_history=request.sanitized_conversation_history # PII-free history only - ) - log_debug(f"API: Response ready ({len(result.response) if result.response else 0} chars)") - - # Add captured console logs to the response - result.console_logs = console_logs - return result - except Exception as e: - import traceback - log_student(f"API ERROR: {e}") - log_debug(f"API ERROR TRACEBACK: {traceback.format_exc()}") - # Return error response instead of raising to ensure client gets details - from .models import ChatResponse as CR - error_response = CR( - id="error", - response=f"Server error: {type(e).__name__}: {str(e)}", - tool_calls=[], - variation_key="error", - model="error", - agent_configurations=[], - console_logs=console_logs + [ - f"API EXCEPTION: {type(e).__name__}: {str(e)}", - f"TRACEBACK: {traceback.format_exc()[:1000]}" - ] - ) - return error_response + + # SECURITY BOUNDARY: Pass sanitized conversation history only + # Raw messages with PII are never sent to support agent - strict isolation maintained + result = await agent_service.process_message( + user_id=request.user_id, + message=request.message, # Raw message (security agent processes this) + user_context=request.user_context, + sanitized_conversation_history=request.sanitized_conversation_history # PII-free history only + ) + log_debug(f"API: Response ready ({len(result.response)} chars)") + + # Add captured console logs to the response + result.console_logs = console_logs + return result @app.post("/admin/flush") async def flush_metrics(): """Force LaunchDarkly metrics to flush immediately - for simulation""" log_student("ADMIN: Flushing LaunchDarkly metrics...") - - try: - # Flush the LaunchDarkly client to send metrics immediately - agent_service.flush_metrics() - return {"success": True, "message": "Metrics flushed to LaunchDarkly"} - except Exception as e: - log_student(f"ADMIN FLUSH ERROR: {e}") - return {"success": False, "message": f"Failed to flush metrics: {e}"} - -# Cache clearing removed - simplified for demo + agent_service.config_manager.flush_metrics() + return {"success": True, "message": "Metrics flushed to LaunchDarkly"} @app.post("/feedback", response_model=FeedbackResponse) async def submit_feedback(feedback: FeedbackRequest): """Submit user feedback for AI responses""" + log_student(f"FEEDBACK: {feedback.feedback} from {feedback.source}") + config_manager = agent_service.config_manager + try: - log_student(f"FEEDBACK: {feedback.feedback} from {feedback.source}") - - # Get LaunchDarkly tracker and submit feedback - try: - # Get a real LaunchDarkly AI config to get the tracker with user context - support_config = await agent_service.config_manager.get_config( - feedback.user_id, - "support-agent", - feedback.user_context - ) + # Feedback is attributed to the support-agent variation this user is served + support_config = await config_manager.get_config( + feedback.user_id, + "support-agent", + feedback.user_context + ) - # Convert feedback format - thumbs_up = feedback.feedback == "positive" + # Same context the config was evaluated with, so feedback is attributed to the served variation + ld_context = config_manager.build_context(feedback.user_id, feedback.user_context) + success = config_manager.track_feedback( + support_config, + ld_context, + thumbs_up=feedback.feedback == "positive" + ) + except Exception as e: + log_student(f"FEEDBACK ERROR: {e}") + return FeedbackResponse(success=False, message=f"Failed to submit feedback: {e}") - # Track feedback using config_manager - success = agent_service.config_manager.track_feedback( - support_config.create_tracker(), - thumbs_up=thumbs_up - ) + if not success: + log_debug("FEEDBACK: Failed to submit feedback to LaunchDarkly") + return FeedbackResponse(success=False, message="Failed to submit feedback to metrics tracking") - if success: - log_debug(f"FEEDBACK SUBMITTED: {feedback.feedback} for {feedback.variation_key}") - return FeedbackResponse( - success=True, - message=f"Feedback submitted successfully" - ) - else: - log_debug(f"FEEDBACK: Failed to submit feedback to LaunchDarkly") - return FeedbackResponse( - success=False, - message="Failed to submit feedback to metrics tracking" - ) - - except Exception as e: - log_student(f"FEEDBACK ERROR: {e}") - return FeedbackResponse( - success=False, - message=f"Failed to submit feedback: {e}" - ) - - except Exception as e: - log_student(f"FEEDBACK ENDPOINT ERROR: {e}") - return FeedbackResponse( - success=False, - message=f"Internal error: {e}" - ) \ No newline at end of file + log_debug(f"FEEDBACK SUBMITTED: {feedback.feedback} for support-agent variation {support_config.variation_key}") + return FeedbackResponse(success=True, message="Feedback submitted successfully") diff --git a/api/models.py b/api/models.py index 8c3af85..f6eb5b7 100644 --- a/api/models.py +++ b/api/models.py @@ -27,6 +27,9 @@ class ChatResponse(BaseModel): tool_calls: List[str] variation_key: str model: str + trace_id: Optional[str] = None + span_id: Optional[str] = None + trace_timestamp: Optional[str] = None agent_configurations: Optional[List[AgentConfig]] = None console_logs: Optional[List[str]] = None diff --git a/api/segmentation_test.py b/api/segmentation_test.py index 2a9226b..8a4ce57 100644 --- a/api/segmentation_test.py +++ b/api/segmentation_test.py @@ -4,221 +4,156 @@ Tests the geographic + business tier targeting matrix to ensure correct model and tool routing. """ +import os import requests -import json from typing import Dict, Any +from dotenv import load_dotenv + +load_dotenv() + +API_BASE_URL = f"http://{os.getenv('API_HOST', 'localhost')}:{os.getenv('API_PORT', '8000')}" def test_user_scenario(user_context: Dict[str, Any], expected_config: Dict[str, Any]) -> Dict[str, Any]: """Test a specific user scenario and validate the configuration""" # Test query with PII to verify security agent behavior test_query = "My name is John Doe, email: john.doe@example.com. I'm a VP at StarSystems and need help with documentation research" - + payload = { "message": test_query, "user_id": user_context.get("user_id", "test-user"), "user_context": user_context } - + try: - response = requests.post("http://localhost:8000/chat", json=payload, timeout=45) - + # Paid users can make many tool calls, and the first MCP call starts the MCP servers + response = requests.post(f"{API_BASE_URL}/chat", json=payload, timeout=300) + if response.status_code != 200: return { "success": False, - "error": f"API Error: {response.status_code}", - "details": response.text + "error": f"API Error: {response.status_code}: {response.text}", + "user_context": user_context } - - result = response.json() - - # Extract actual configuration from response - actual_config = { - "support-agent": {}, - "security-agent": {}, - "supervisor-agent": {} - } - - # Parse agent configurations from response - agent_configs = result.get("agent_configurations", []) - for agent_config in agent_configs: - agent_name = agent_config.get("agent_name", "unknown") - if agent_name in actual_config: - actual_config[agent_name] = { - "model": agent_config.get("model", "unknown"), - "variation_key": agent_config.get("variation_key", "unknown"), - "tools": agent_config.get("tools", []), - "tool_details": agent_config.get("tool_details", []) - } - - # Check for MCP tools specifically - support_tools = actual_config.get("support-agent", {}).get("tools", []) - has_mcp_tools = any(tool in support_tools for tool in ["arxiv_search", "semantic_scholar"]) - - # Check security agent redaction behavior - response_text = result.get("response", "") - redacted_text = result.get("redacted_text", "") - - # Check if PII was properly redacted (should not contain original PII in final response) - pii_properly_redacted = ( - "John Doe" not in response_text and - "john.doe@example.com" not in response_text and - "[REDACTED]" in redacted_text # Should have redacted text in workflow - ) - - # For EU users, check if job title and company were redacted (strict security) - strict_redaction_working = True - if user_context.get("country") in ["DE", "FR", "ES", "IT"]: # EU countries - strict_redaction_working = ( - "VP" not in redacted_text and - "StarSystems" not in redacted_text and - "[REDACTED]" in redacted_text - ) - return { - "success": True, - "user_context": user_context, - "expected": expected_config, - "actual": actual_config, - "has_mcp_tools": has_mcp_tools, - "pii_properly_redacted": pii_properly_redacted, - "strict_redaction_working": strict_redaction_working, - "redacted_text": redacted_text, - "response_length": len(result.get("response", "")), - "tool_calls": result.get("tool_calls", []), - "response": result.get("response", "")[:200] + "..." if len(result.get("response", "")) > 200 else result.get("response", "") - } - + result = response.json() except requests.exceptions.RequestException as e: return { "success": False, "error": f"Request failed: {e}", "user_context": user_context } - except json.JSONDecodeError as e: - return { - "success": False, - "error": f"JSON decode error: {e}", - "user_context": user_context + + # Extract actual configuration from response + actual_config = { + agent_config["agent_name"]: { + "model": agent_config.get("model", "unknown"), + "variation_key": agent_config.get("variation_key", "unknown"), + "tools": agent_config.get("tools", []), } + for agent_config in result.get("agent_configurations") or [] + } + + # Check for MCP tools specifically + support_tools = actual_config.get("support-agent", {}).get("tools", []) + has_mcp_tools = any(tool in support_tools for tool in ["arxiv_search", "openalex_search"]) + + response_text = result.get("response", "") + return { + "success": True, + "user_context": user_context, + "expected": expected_config, + "actual": actual_config, + "has_mcp_tools": has_mcp_tools, + "response_length": len(response_text), + "tool_calls": result.get("tool_calls", []), + "response": response_text[:200] + "..." if len(response_text) > 200 else response_text + } def validate_configuration(test_result: Dict[str, Any]) -> Dict[str, bool]: """Validate if the actual configuration matches expected""" - + if not test_result.get("success"): return {"overall": False, "error": test_result.get("error", "Unknown error")} - - expected = test_result["expected"] - actual = test_result["actual"] - user_context = test_result["user_context"] - + + support_actual = test_result["actual"].get("support-agent", {}) + support_expected = test_result["expected"].get("support_agent", {}) + validations = {} - - # Check support agent configuration - support_actual = actual.get("support-agent", {}) - support_expected = expected.get("support_agent", {}) - + # Model validation actual_model = support_actual.get("model", "").lower() expected_model = support_expected.get("model", "").lower() validations["model_match"] = expected_model in actual_model or actual_model in expected_model - - # Variation validation - actual_variation = support_actual.get("variation_key", "") - expected_variation = support_expected.get("variation_key", "") - validations["variation_match"] = actual_variation == expected_variation - + + # Variation validation + validations["variation_match"] = support_actual.get("variation_key", "") == support_expected.get("variation_key", "") + # Tools validation - actual_tools = support_actual.get("tools", []) expected_tools = support_expected.get("tools", []) - validations["tools_match"] = set(expected_tools).issubset(set(actual_tools)) if expected_tools else True - + validations["tools_match"] = set(expected_tools).issubset(support_actual.get("tools", [])) + # MCP tools validation for paid users - has_mcp = test_result.get("has_mcp_tools", False) - should_have_mcp = user_context.get("plan") == "paid" - validations["mcp_tools_correct"] = has_mcp == should_have_mcp - - # Overall validation - validations["overall"] = all([ - validations.get("model_match", False), - validations.get("variation_match", False), - validations.get("tools_match", False), - validations.get("mcp_tools_correct", False) - ]) - + should_have_mcp = test_result["user_context"].get("plan") == "paid" + validations["mcp_tools_correct"] = test_result["has_mcp_tools"] == should_have_mcp + + validations["overall"] = all(validations.values()) return validations def print_detailed_results(test_result: Dict[str, Any], validations: Dict[str, bool]): """Print detailed test results""" - + + def status(check): + return "βœ…" if validations.get(check) else "❌" + user_ctx = test_result["user_context"] user_desc = f"{user_ctx['country']} {user_ctx['plan']} user" - + print(f"\n{'='*60}") print(f"πŸ§ͺ TESTING: {user_desc} (ID: {user_ctx['user_id']})") print(f"{'='*60}") - + if not test_result.get("success"): - print(f" TEST FAILED: {test_result.get('error', 'Unknown error')}") + print(f"❌ TEST FAILED: {test_result.get('error', 'Unknown error')}") return - - expected = test_result["expected"] - actual = test_result["actual"] - + + support_actual = test_result["actual"].get("support-agent", {}) + support_expected = test_result["expected"].get("support_agent", {}) + # Support Agent Results - print(f" SUPPORT AGENT:") - support_actual = actual.get("support-agent", {}) - support_expected = expected.get("support_agent", {}) - - # Model comparison - actual_model = support_actual.get("model", "unknown") - expected_model = support_expected.get("model", "unknown") - model_status = "" if validations.get("model_match") else "" - print(f" Model: {actual_model} (expected: {expected_model}) {model_status}") - - # Variation comparison - actual_variation = support_actual.get("variation_key", "unknown") - expected_variation = support_expected.get("variation_key", "unknown") - variation_status = "" if validations.get("variation_match") else "" - print(f" Variation: {actual_variation} (expected: {expected_variation}) {variation_status}") - - # Tools comparison - actual_tools = support_actual.get("tools", []) - expected_tools = support_expected.get("tools", []) - tools_status = "" if validations.get("tools_match") else "" - print(f" Tools: {actual_tools} {tools_status}") - print(f" Expected: {expected_tools}") - - # MCP tools check - has_mcp = test_result.get("has_mcp_tools", False) + print("πŸ“Š SUPPORT AGENT:") + print(f" Model: {support_actual.get('model', 'unknown')} (expected: {support_expected.get('model', 'unknown')}) {status('model_match')}") + print(f" Variation: {support_actual.get('variation_key', 'unknown')} (expected: {support_expected.get('variation_key', 'unknown')}) {status('variation_match')}") + print(f" Tools: {support_actual.get('tools', [])} {status('tools_match')}") + print(f" Expected: {support_expected.get('tools', [])}") + should_have_mcp = user_ctx.get("plan") == "paid" - mcp_status = "" if validations.get("mcp_tools_correct") else "" - print(f" MCP Tools: {'Yes' if has_mcp else 'No'} (should be: {'Yes' if should_have_mcp else 'No'}) {mcp_status}") - + print(f" MCP Tools: {'Yes' if test_result['has_mcp_tools'] else 'No'} (should be: {'Yes' if should_have_mcp else 'No'}) {status('mcp_tools_correct')}") + # Response info - print(f" RESPONSE:") - print(f" Length: {test_result.get('response_length', 0)} chars") - print(f" Tools Called: {test_result.get('tool_calls', [])}") - print(f" Preview: {test_result.get('response', 'No response')[:100]}...") - + print("\nπŸ“ RESPONSE:") + print(f" Length: {test_result['response_length']} chars") + print(f" Tools Called: {test_result['tool_calls']}") + print(f" Preview: {test_result['response'][:100]}...") + # Overall result - overall_status = " PASSED" if validations.get("overall") else " FAILED" - print(f"\n RESULT: {overall_status}") + overall_status = "βœ… PASSED" if validations.get("overall") else "❌ FAILED" + print(f"\n🎯 RESULT: {overall_status}") def main(): """Run all segmentation tests""" - print(" COMPREHENSIVE TUTORIAL 2 SEGMENTATION TESTS") + print("πŸš€ COMPREHENSIVE TUTORIAL 2 SEGMENTATION TESTS") print("Testing Geographic + Business Tier Targeting Matrix") print("=" * 70) - + test_scenarios = [ { "user_context": {"country": "DE", "plan": "paid", "user_id": "user_eu_paid_001", "region": "europe"}, "expected_config": { "support_agent": { - "model": "claude-sonnet-4-6", + "model": "claude-sonnet-5-5", "variation_key": "eu-paid", - "tools": ["search_v1", "search_v2", "reranking", "arxiv_search", "semantic_scholar"] + "tools": ["search_v1", "search_v2", "reranking", "arxiv_search", "openalex_search"] } }, "description": "EU Paid β†’ Claude Sonnet + Full MCP Tools" @@ -227,8 +162,8 @@ def main(): "user_context": {"country": "DE", "plan": "free", "user_id": "user_eu_free_001", "region": "europe"}, "expected_config": { "support_agent": { - "model": "claude-haiku-4-5-20251001", - "variation_key": "eu-free", + "model": "claude-haiku-5-5", + "variation_key": "eu-free", "tools": ["search_v1"] } }, @@ -238,68 +173,63 @@ def main(): "user_context": {"country": "US", "plan": "paid", "user_id": "user_other_paid_001", "region": "other"}, "expected_config": { "support_agent": { - "model": "chatgpt-4o-latest", + "model": "gpt-6.2-sol", "variation_key": "other-paid", - "tools": ["search_v1", "search_v2", "reranking", "arxiv_search", "semantic_scholar"] + "tools": ["search_v1", "search_v2", "reranking", "arxiv_search", "openalex_search"] } }, - "description": "US Paid β†’ GPT-4 + Full MCP Tools" + "description": "US Paid β†’ GPT-6.2 Sol + Full MCP Tools" }, { "user_context": {"country": "US", "plan": "free", "user_id": "user_other_free_001", "region": "other"}, "expected_config": { "support_agent": { - "model": "gpt-4o-mini-2024-07-18", + "model": "gpt-6-luna", "variation_key": "other-free", "tools": ["search_v1"] } }, - "description": "US Free β†’ GPT-4o Mini + Basic Tools" + "description": "US Free β†’ GPT-6 Luna + Basic Tools" } ] - - passed_tests = 0 - failed_tests = 0 + total_tests = len(test_scenarios) - + passed_tests = 0 + for scenario in test_scenarios: print(f"\nπŸ”„ Running: {scenario['description']}") - - test_result = test_user_scenario( - scenario["user_context"], - scenario["expected_config"] - ) - + + test_result = test_user_scenario(scenario["user_context"], scenario["expected_config"]) validations = validate_configuration(test_result) print_detailed_results(test_result, validations) - + if validations.get("overall"): passed_tests += 1 - else: - failed_tests += 1 - + + failed_tests = total_tests - passed_tests + # Final Summary print("\n" + "=" * 70) - print(f" FINAL RESULTS") - print(f"=" * 70) - print(f" PASSED: {passed_tests}/{total_tests}") - print(f" FAILED: {failed_tests}/{total_tests}") - + print("πŸ“Š FINAL RESULTS") + print("=" * 70) + print(f"βœ… PASSED: {passed_tests}/{total_tests}") + print(f"❌ FAILED: {failed_tests}/{total_tests}") + if passed_tests == total_tests: - print(f"\nπŸŽ‰ ALL TESTS PASSED! LaunchDarkly targeting is working correctly.") - print(f" β€’ Geographic segmentation: Working") - print(f" β€’ Business tier routing: Working") - print(f" β€’ Model assignment: Working") - print(f" β€’ Tool configuration: Working") - print(f" β€’ MCP integration: Working") + print("\nπŸŽ‰ ALL TESTS PASSED! LaunchDarkly targeting is working correctly.") + print(" β€’ Geographic segmentation: Working") + print(" β€’ Business tier routing: Working") + print(" β€’ Model assignment: Working") + print(" β€’ Tool configuration: Working") + print(" β€’ MCP integration: Working") else: - print(f"\n {failed_tests} TEST(S) FAILED - LaunchDarkly configuration needs attention.") - print(f" 1. Check segment rules in LaunchDarkly dashboard") - print(f" 2. Verify targeting rules for support-agent AI config") - print(f" 3. Ensure segments are properly matching user contexts") - print(f" 4. Wait a few minutes for LaunchDarkly propagation") - - print(f"\nπŸ”— Next: Test manually in UI at http://localhost:8501") + print(f"\n⚠️ {failed_tests} TEST(S) FAILED - LaunchDarkly configuration needs attention.") + print(" 1. Check segment rules in LaunchDarkly dashboard") + print(" 2. Verify targeting rules for support-agent AI config") + print(" 3. Ensure segments are properly matching user contexts") + print(" 4. Wait a few minutes for LaunchDarkly propagation") + + print("\nπŸ”— Next: Test manually in UI at http://localhost:8501") if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/api/services/agent_service.py b/api/services/agent_service.py index added11..2ca122b 100644 --- a/api/services/agent_service.py +++ b/api/services/agent_service.py @@ -1,16 +1,14 @@ import uuid -from typing import List +from datetime import datetime, timezone from langchain_core.messages import HumanMessage, AIMessage -from dotenv import load_dotenv +from launchdarkly_ai_server import conversation_id +from opentelemetry import trace from ..models import ChatResponse, AgentConfig as APIAgentConfig -from agents.supervisor_agent import create_supervisor_agent -from agents.support_agent import create_support_agent -from agents.security_agent import create_security_agent -from config_manager import FixedConfigManager as ConfigManager -from utils.logger import log_student, log_debug, log_info +from agents.supervisor_agent import create_supervisor_agent, trim_message_history +from config_manager import FixedConfigManager as ConfigManager, TRACER_NAME +from utils.logger import log_student, log_debug -# Ensure .env is loaded before ConfigManager initialization -load_dotenv() +MAX_MESSAGE_LENGTH = 5000 class AgentService: """ @@ -34,58 +32,6 @@ class AgentService: def __init__(self): # Initialize LaunchDarkly configuration manager self.config_manager = ConfigManager() - # Clear LaunchDarkly cache on startup to get latest configs - self.config_manager.clear_cache() - - def flush_metrics(self): - """Flush LaunchDarkly metrics immediately""" - try: - # Use the config manager's close method which handles flushing - self.config_manager.close() - print(" METRICS: Successfully flushed to LaunchDarkly") - except Exception as e: - print(f" METRICS FLUSH ERROR: {e}") - raise - - def _validate_inputs(self, message: str, user_id: str, user_context: dict, sanitized_conversation_history: list) -> tuple[str, dict, list]: - """Validate and sanitize all inputs""" - # Validate message content - if not message or not message.strip(): - raise ValueError("Please provide a message to process.") - - # Validate message length (prevent extremely long inputs) - max_message_length = 5000 - if len(message) > max_message_length: - raise ValueError(f"Message too long ({len(message)} characters). Please limit to {max_message_length} characters.") - - # Validate and sanitize user_id - clean_user_id = user_id.strip() if user_id and user_id.strip() else "anonymous_user" - if clean_user_id != user_id: - log_debug("VALIDATION: Empty user_id provided, using 'anonymous_user'") - - # Validate user_context structure - clean_user_context = user_context if isinstance(user_context, dict) else {} - if user_context is not None and not isinstance(user_context, dict): - log_debug("VALIDATION: Invalid user_context type, using empty dict") - - # Validate sanitized_conversation_history - clean_history = sanitized_conversation_history if isinstance(sanitized_conversation_history, list) else None - if sanitized_conversation_history is not None and not isinstance(sanitized_conversation_history, list): - log_debug("VALIDATION: Invalid conversation history type, ignoring") - - log_debug("βœ… INPUT VALIDATION: All inputs validated successfully") - return clean_user_id, clean_user_context, clean_history - - def _create_error_response(self, error_message: str, error_type: str = "validation_error") -> ChatResponse: - """Create standardized error response""" - return ChatResponse( - id=str(uuid.uuid4()), - response=error_message, - tool_calls=[], - variation_key=error_type, - model=error_type, - agent_configurations=[] - ) async def process_message(self, user_id: str, message: str, user_context: dict = None, sanitized_conversation_history: list = None) -> ChatResponse: """ @@ -112,30 +58,34 @@ async def process_message(self, user_id: str, message: str, user_context: dict = log_debug(f"AGENT SERVICE: Processing message for {user_id}") # Validate inputs - try: - user_id, user_context, sanitized_conversation_history = self._validate_inputs( - message, user_id, user_context, sanitized_conversation_history + if len(message) > MAX_MESSAGE_LENGTH: + return ChatResponse( + id=str(uuid.uuid4()), + response=f"Message too long ({len(message)} characters). Please limit to {MAX_MESSAGE_LENGTH} characters.", + tool_calls=[], + variation_key="validation_error", + model="validation_error", + agent_configurations=[] ) - except ValueError as e: - return self._create_error_response(str(e)) + user_id = user_id.strip() or "anonymous_user" + user_context = user_context or {} - # Get LaunchDarkly LDAI configurations for all agents - log_debug(" AGENT SERVICE: Loading agent configurations...") - supervisor_config = await self.config_manager.get_config(user_id, "supervisor-agent", user_context) + # Get LaunchDarkly LDAI configurations for all agents (initializes OTel tracer provider on first call) + supervisor_config = await self.config_manager.get_config(user_id, "supervisor-agent", user_context) support_config = await self.config_manager.get_config(user_id, "support-agent", user_context) security_config = await self.config_manager.get_config(user_id, "security-agent", user_context) - - log_student(f"LDAI: 3 agents configured") - log_debug(f"LDAI: Supervisor({supervisor_config.model.name}), Support({support_config.model.name}), Security({security_config.model.name})") - + + log_student("LDAI: 3 agents configured") + log_debug(f"LDAI: Supervisor({supervisor_config.model_name}), Support({support_config.model_name}), Security({security_config.model_name})") + # Create supervisor agent with all child agents using LDAI SDK pattern supervisor_agent = create_supervisor_agent( - supervisor_config, - support_config, + supervisor_config, + support_config, security_config, self.config_manager ) - + # ============================================= # PII SECURITY BOUNDARY SETUP # ============================================= @@ -143,38 +93,21 @@ async def process_message(self, user_id: str, message: str, user_context: dict = # Convert sanitized conversation history to LangChain messages # CRITICAL: Support agent will ONLY see these sanitized messages sanitized_langchain_messages = [] - if sanitized_conversation_history: - for msg in sanitized_conversation_history: - # Validate message structure - if not isinstance(msg, dict): - log_debug("VALIDATION: Skipping invalid message in conversation history") - continue - - role = msg.get("role") - content = msg.get("content") - - # Validate content exists and is not empty - if not content or not content.strip(): - log_debug(f"VALIDATION: Skipping empty message with role {role}") - continue - - # Convert to LangChain messages - if role == "user": - sanitized_langchain_messages.append(HumanMessage(content=content.strip())) - elif role == "assistant": - sanitized_langchain_messages.append(AIMessage(content=content.strip())) - else: - log_debug(f"VALIDATION: Skipping message with unknown role: {role}") - - # === MESSAGE MEMORY MANAGEMENT === - # Trim conversation history to prevent context overflow - # This is especially important for long-running conversations - from agents.supervisor_agent import trim_message_history - sanitized_langchain_messages = trim_message_history(sanitized_langchain_messages, max_messages=8) - - # Add current raw message for security agent processing - current_raw_message = HumanMessage(content=message) - + for msg in sanitized_conversation_history or []: + role = msg.get("role") + content = (msg.get("content") or "").strip() + if not content: + continue + if role == "user": + sanitized_langchain_messages.append(HumanMessage(content=content)) + elif role == "assistant": + sanitized_langchain_messages.append(AIMessage(content=content)) + + # === MESSAGE MEMORY MANAGEMENT === + # Trim conversation history to prevent context overflow + # This is especially important for long-running conversations + sanitized_langchain_messages = trim_message_history(sanitized_langchain_messages, max_messages=8) + # ============================================= # LANGGRAPH INITIAL STATE CONSTRUCTION # ============================================= @@ -184,12 +117,12 @@ async def process_message(self, user_id: str, message: str, user_context: dict = initial_state = { # === CORE MESSAGE FLOW === "user_input": message.strip(), # Raw message (security agent only) - trimmed - "messages": [current_raw_message], # Security agent gets raw message + "messages": [HumanMessage(content=message)], # Security agent gets raw message "final_response": "", # === LAUNCHDARKLY TARGETING === - "user_id": user_id, # Validated user ID - "user_context": user_context or {}, # Validated user context + "user_id": user_id, + "user_context": user_context, # === WORKFLOW ORCHESTRATION === "current_agent": "", # Supervisor will determine first agent @@ -202,113 +135,89 @@ async def process_message(self, user_id: str, message: str, user_context: dict = "support_tool_details": [], # === PII SECURITY BOUNDARY === - "sanitized_messages": sanitized_langchain_messages, # SUPPORT AGENT ONLY gets these (validated) + "sanitized_messages": sanitized_langchain_messages, # SUPPORT AGENT ONLY gets these "processed_user_input": "", # Will be set by security agent "pii_detected": False, # Will be set by security agent "pii_types": [], # Will be set by security agent "redacted_text": message.strip(), # Will be updated by security agent } - + # ============================================= - # LANGGRAPH WORKFLOW EXECUTION + # LANGGRAPH WORKFLOW EXECUTION (WITH OTEL ROOT TRACE) # ============================================= - log_student(f"INTELLIGENT ROUTING: Starting PII pre-screening analysis") - log_debug(f"πŸ”’ PII PROTECTION: Enhanced supervisor will decide routing path") + log_student("INTELLIGENT ROUTING: Starting PII pre-screening analysis") + + tracer = trace.get_tracer(TRACER_NAME) + trace_id_hex = None + span_id_hex = None + trace_timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ") + with conversation_id(user_id), tracer.start_as_current_span("multi-agent-chat") as root_span: + root_span.set_attribute("launchdarkly.operation.type", "gen_ai") + root_span.set_attribute("context.contextKeys.user", user_id) + span_ctx = root_span.get_span_context() + if span_ctx and span_ctx.trace_id: + trace_id_hex = format(span_ctx.trace_id, "032x") + span_id_hex = format(span_ctx.span_id, "016x") + result = await supervisor_agent.ainvoke(initial_state) + + if hasattr(self.config_manager, "flush_traces"): + self.config_manager.flush_traces() - # Execute the LangGraph workflow - # The supervisor will orchestrate security and support agents automatically - result = await supervisor_agent.ainvoke(initial_state) - actual_tool_calls = result.get("support_tool_calls", []) - tool_details = result.get("support_tool_details", []) - - # Get security agent PII detection results and tool details security_detected = result.get("pii_detected", False) - security_types = result.get("pii_types", []) - security_redacted = result.get("redacted_text", message) - security_tool_details = result.get("security_tool_details", []) - + log_student(f"WORKFLOW COMPLETE: PII detected: {security_detected}") - - # Create agent configuration metadata showing actual usage - # Extract actual variation key from LaunchDarkly AI config - def get_variation_key(ai_config, agent_name): - try: - # The variation key is stored in the tracker object - tracker = ai_config.create_tracker() - if hasattr(tracker, '_variation_key'): - variation_key = tracker._variation_key - log_debug(f"VARIATION EXTRACTED for {agent_name}: {variation_key}") - return variation_key - else: - log_debug(f"VARIATION NOT FOUND for {agent_name}: no tracker._variation_key") - return 'default' - except Exception as e: - log_debug(f"VARIATION EXTRACTION ERROR for {agent_name}: {e}") - return 'default' - + def get_tools_list(ai_config): - try: - config_dict = ai_config.to_dict() - tools = config_dict.get('model', {}).get('parameters', {}).get('tools', []) - tool_names = [tool.get('name', 'unknown') for tool in tools] - log_debug(f"EXTRACTED TOOLS: {tool_names}") - return tool_names - except Exception as e: - log_debug(f"TOOLS EXTRACTION ERROR: {e}") - return [] - - # Extract tools list from configs - security_tools = get_tools_list(security_config) - support_tools = get_tools_list(support_config) - - # Determine which tools were actually used by each agent - security_tools_used = [] - support_tools_used = actual_tool_calls # Support agent is the primary tool user - + return [tool.get('name', 'unknown') for tool in ai_config.parameters.get('tools', [])] + + # Create agent configuration metadata showing actual usage agent_configurations = [ APIAgentConfig( agent_name="supervisor-agent", - variation_key=get_variation_key(supervisor_config, "supervisor-agent"), - model=supervisor_config.model.name, + variation_key=supervisor_config.variation_key, + model=supervisor_config.model_name, tools=[], # Supervisor doesn't have tools available tools_used=[] # Supervisor doesn't use tools directly ), APIAgentConfig( - agent_name="security-agent", - variation_key=get_variation_key(security_config, "security-agent"), - model=security_config.model.name, - tools=security_tools, # Show configured tools - tools_used=security_tools_used, # Show actual tools used - tool_details=security_tool_details, # Show security tool details with PII results + agent_name="security-agent", + variation_key=security_config.variation_key, + model=security_config.model_name, + tools=get_tools_list(security_config), + tools_used=[], + tool_details=[], # Pass PII detection results to UI detected=security_detected, - types=security_types, - redacted=security_redacted + types=result.get("pii_types", []), + redacted=result.get("redacted_text", message) ), APIAgentConfig( agent_name="support-agent", - variation_key=get_variation_key(support_config, "support-agent"), - model=support_config.model.name, - tools=support_tools, # Show configured tools from LaunchDarkly - tools_used=support_tools_used, # Show actual tools executed - tool_details=tool_details # Show detailed tool info with search queries + variation_key=support_config.variation_key, + model=support_config.model_name, + tools=get_tools_list(support_config), # Show configured tools from LaunchDarkly + tools_used=actual_tool_calls, # Show actual tools executed + tool_details=result.get("support_tool_details", []) # Show detailed tool info with search queries ) ] - + return ChatResponse( id=str(uuid.uuid4()), response=result["final_response"], tool_calls=actual_tool_calls, # Show actual tools used - variation_key=get_variation_key(supervisor_config, "supervisor-agent"), # Use actual LaunchDarkly variation - model=supervisor_config.model.name, # Primary model + variation_key=supervisor_config.variation_key, # Use actual LaunchDarkly variation + model=supervisor_config.model_name, # Primary model + trace_id=trace_id_hex, + span_id=span_id_hex, + trace_timestamp=trace_timestamp, agent_configurations=agent_configurations ) - + except Exception as e: log_student(f"LDAI WORKFLOW ERROR: {e}") - + # Return error response return ChatResponse( id=str(uuid.uuid4()), @@ -317,4 +226,4 @@ def get_tools_list(ai_config): variation_key="error", model="error", agent_configurations=[] - ) \ No newline at end of file + ) diff --git a/api/utils/console_capture.py b/api/utils/console_capture.py index 717cd90..83405ff 100644 --- a/api/utils/console_capture.py +++ b/api/utils/console_capture.py @@ -1,61 +1,44 @@ import sys -import io -from typing import List from contextlib import contextmanager +from contextvars import ContextVar + +# Each request collects its own logs; concurrent requests run in separate contexts +_current_logs: ContextVar[list | None] = ContextVar("console_logs", default=None) + + +class _CapturingWriter: + """Records each non-empty write for the current request and passes it through, so logs still show in the console""" + def __init__(self, stream, prefix=""): + self.stream = stream + self.prefix = prefix + + def write(self, text): + captured_logs = _current_logs.get() + if captured_logs is not None and text.strip(): # Only capture non-empty lines + captured_logs.append(f"{self.prefix}{text.strip()}") + self.stream.write(text) + self.stream.flush() + + def flush(self): + self.stream.flush() + + def fileno(self): + # Delegate to the original stream for subprocess compatibility + return self.stream.fileno() + @contextmanager def capture_console_output(): """Context manager that captures both stdout and stderr during execution""" + # The writers are installed once and left in place: swapping sys.stdout per + # request breaks when requests overlap and restore each other's streams. + if not isinstance(sys.stdout, _CapturingWriter): + sys.stdout = _CapturingWriter(sys.stdout) + sys.stderr = _CapturingWriter(sys.stderr, prefix="[ERROR] ") + captured_logs = [] - - # Create custom write function that captures output - def capture_write(text): - if text.strip(): # Only capture non-empty lines - captured_logs.append(text.strip()) - # Also write to original stdout so we can still see logs in console - original_stdout.write(text) - original_stdout.flush() - - # Store original stdout/stderr - original_stdout = sys.stdout - original_stderr = sys.stderr - + token = _current_logs.set(captured_logs) try: - # Create a custom stdout that captures and passes through - class CapturingWriter: - def write(self, text): - capture_write(text) - - def flush(self): - original_stdout.flush() - - def fileno(self): - # Delegate to original stdout for subprocess compatibility - return original_stdout.fileno() - - # Replace stdout with our capturing writer - sys.stdout = CapturingWriter() - - # Also capture stderr (for any error prints) - class CapturingStdErr: - def write(self, text): - if text.strip(): - captured_logs.append(f"[ERROR] {text.strip()}") - original_stderr.write(text) - original_stderr.flush() - - def flush(self): - original_stderr.flush() - - def fileno(self): - # Delegate to original stderr for subprocess compatibility - return original_stderr.fileno() - - sys.stderr = CapturingStdErr() - yield captured_logs - finally: - # Restore original stdout/stderr - sys.stdout = original_stdout - sys.stderr = original_stderr \ No newline at end of file + _current_logs.reset(token) diff --git a/bootstrap/ai_config_manifest.yaml b/bootstrap/ai_config_manifest.yaml index 54dcecc..60df2e3 100644 --- a/bootstrap/ai_config_manifest.yaml +++ b/bootstrap/ai_config_manifest.yaml @@ -92,11 +92,11 @@ project: type: "mcp" server: "arxiv-mcp-server" - - key: "semantic_scholar" - name: "Semantic Scholar Research" - description: "Access Semantic Scholar citation database" + - key: "openalex_search" + name: "OpenAlex Research" + description: "Search OpenAlex for scholarly works and citation counts" type: "mcp" - server: "semanticscholar-MCP-Server" + server: "openalex-mcp-server" ai_config: # Supervisor agent for workflow orchestration @@ -106,12 +106,10 @@ project: - key: "supervisor-basic" modelConfig: provider: "anthropic" - modelId: "claude-sonnet-4-6" + modelId: "claude-haiku-5-5" # NOTE: After bootstrap, modify instructions in LaunchDarkly UI, not here instructions: "You are an intelligent routing supervisor for a multi-agent system. Your primary job is to assess whether user input likely contains PII (personally identifiable information) to determine the most efficient processing route.\n\n**PII Assessment:**\nAnalyze the user input and provide:\n- likely_contains_pii: boolean assessment\n- confidence: confidence score (0.0 to 1.0)\n- reasoning: clear explanation of your decision\n- recommended_route: either 'security_agent' or 'support_agent'\n\n**Route to SECURITY_AGENT** if the text likely contains:\n- Email addresses, phone numbers, addresses\n- Names (first/last names, usernames)\n- Financial information (credit cards, SSNs, account numbers)\n- Sensitive personal data\n\n**Route to SUPPORT_AGENT** if the text appears to be:\n- General questions without personal details\n- Technical queries\n- Search requests\n- Educational content requests\n\nAnalyze this user input and recommend the optimal route:" - customParameters: - temperature: 0.0 - + targeting: rules: [] defaultVariation: "supervisor-basic" @@ -123,11 +121,10 @@ project: - key: "basic-security" modelConfig: provider: "anthropic" - modelId: "claude-haiku-4-5-20251001" + modelId: "claude-haiku-5-5" # NOTE: After bootstrap, modify instructions in LaunchDarkly UI, not here instructions: "You are a privacy agent that REMOVES direct PII. Focus on clearly personal identifiers:\n\nEmail addresses\nPhone numbers\nSocial Security Numbers\nFull names (but not generic titles)\nStreet addresses\nCredit card numbers\nDriver's license numbers\n\nResponse Format:\n\ndetected: true if any PII was found, false otherwise\ntypes: array of PII types found (e.g., ['email', 'name', 'phone'])\nredacted: the input text with PII replaced by [REDACTED], keeping the text readable and natural\n\nExamples:\n\nInput: \"I work at Acme Corp in Berlin as a manager\"\n\nOutput: detected=false, types=[], redacted='I work at Acme Corp in Berlin as a manager'\n\n\nInput: \"Contact John Smith at john@email.com or 555-1234\"\n\nOutput: detected=true, types=['name', 'email', 'phone'], redacted='Contact [REDACTED] at [REDACTED] or [REDACTED]'\n\n\nInput: \"The CEO from Microsoft contacted me\"\n\nOutput: detected=false, types=[], redacted='The CEO from Microsoft contacted me'" customParameters: - temperature: 0.1 max_tool_calls: 1 - key: "strict-security" modelConfig: @@ -135,7 +132,6 @@ project: modelId: "mistral-small-latest" instructions: "You are a strict privacy agent that REMOVES ALL PII. Redact everything personally identifiable including names, emails, phones, addresses, locations (cities, countries, regions), job titles, companies, dates of birth, and any identifying references.\n\nYou must return a structured response with these exact fields:\n- detected: boolean (true if ANY PII found, false otherwise)\n- types: array of strings listing PII types found\n- redacted: string with ALL PII replaced by [REDACTED]\n\nPII types to detect: 'name', 'email', 'phone', 'address', 'location', 'job_title', 'company', 'date_of_birth', 'identifying_reference'\n\nExamples:\nInput: \"I work at Acme Corp in Berlin as a manager\" β†’ detected=true, types=[\"company\", \"location\", \"job_title\"], redacted=\"I work at [REDACTED] in [REDACTED] as a [REDACTED]\"\n\nInput: \"I need help with my account\" β†’ detected=false, types=[], redacted=\"I need help with my account\"" customParameters: - temperature: 0.1 max_tool_calls: 1 targeting: rules: @@ -157,25 +153,23 @@ project: - key: "eu-free" modelConfig: provider: "anthropic" - modelId: "claude-haiku-4-5-20251001" + modelId: "claude-haiku-5-5" tools: ["search_v1"] # NOTE: After bootstrap, modify instructions in LaunchDarkly UI, not here instructions: "You are a helpful assistant with access to basic search (search_v1). Use your search tool to find relevant information from the knowledge base while following EU privacy requirements. Always search before responding to ensure accuracy." customParameters: max_tool_calls: 3 - temperature: 0.4 max_cost_per_session: 0.10 privacy_mode: "strict" - key: "eu-paid" modelConfig: provider: "anthropic" - modelId: "claude-sonnet-4-6" - tools: ["search_v1", "search_v2", "reranking", "arxiv_search", "semantic_scholar"] - instructions: "You are a premium research specialist with access to comprehensive RAG tools: search_v1 (basic search), search_v2 (semantic vector search), reranking (BM25 relevance scoring), arxiv_search (academic papers), and semantic_scholar (citation database). When using semantic_scholar, always request as few as possible and less than 5 results (num_results: 5) to optimize performance and avoid rate limiting. When search results are available, prioritize information from those results over your general knowledge. EU privacy laws require strict data handling. Always cite sources and explain confidence levels. Use multiple search approaches for complex queries." + modelId: "claude-sonnet-5-5" + tools: ["search_v1", "search_v2", "reranking", "arxiv_search", "openalex_search"] + instructions: "You are a premium research specialist with access to comprehensive RAG tools: search_v1 (basic search), search_v2 (semantic vector search), reranking (BM25 relevance scoring), arxiv_search (academic papers), and openalex_search (scholarly works with citation counts). When search results are available, prioritize information from those results over your general knowledge. EU privacy laws require strict data handling. Always cite sources and explain confidence levels. Use multiple search approaches for complex queries." customParameters: max_tool_calls: 20 - temperature: 0.1 max_cost_per_session: 10.00 privacy_mode: "strict" @@ -183,24 +177,22 @@ project: - key: "other-free" modelConfig: provider: "openai" - modelId: "gpt-4o-mini" + modelId: "gpt-6-luna" tools: ["search_v1"] instructions: "You are a helpful assistant with access to basic search (search_v1). Use your search tool to find relevant information from the knowledge base. Provide accurate, concise responses efficiently." customParameters: max_tool_calls: 3 - temperature: 0.5 max_cost_per_session: 0.10 privacy_mode: "standard" - key: "other-paid" modelConfig: provider: "openai" - modelId: "gpt-4o" - tools: ["search_v1", "search_v2", "reranking", "arxiv_search", "semantic_scholar"] - instructions: "You are a premium research specialist with access to comprehensive RAG tools: search_v1 (basic search), search_v2 (semantic vector search), reranking (BM25 relevance scoring), arxiv_search (academic papers), and semantic_scholar (citation database). When using semantic_scholar, always request as few as possible and less than 5 results (num_results: 5) to optimize performance and avoid rate limiting. When search results are available, prioritize information from those results over your general knowledge. Provide comprehensive, well-researched responses with source attribution from external databases and academic sources." + modelId: "gpt-6.2-sol" + tools: ["search_v1", "search_v2", "reranking", "arxiv_search", "openalex_search"] + instructions: "You are a premium research specialist with access to comprehensive RAG tools: search_v1 (basic search), search_v2 (semantic vector search), reranking (BM25 relevance scoring), arxiv_search (academic papers), and openalex_search (scholarly works with citation counts). When search results are available, prioritize information from those results over your general knowledge. Provide comprehensive, well-researched responses with source attribution from external databases and academic sources." customParameters: max_tool_calls: 20 - temperature: 0.2 max_cost_per_session: 10.00 privacy_mode: "standard" @@ -208,12 +200,11 @@ project: - key: "international-standard" modelConfig: provider: "anthropic" # Default to privacy-friendly - modelId: "claude-haiku-4-5-20251001" + modelId: "claude-haiku-5-5" tools: ["search_v1", "search_v2", "reranking"] instructions: "You are a helpful assistant with access to RAG tools: search_v1 (basic search), search_v2 (semantic vector search), and reranking (BM25 relevance scoring). When search results are available, prioritize information from those results over your general knowledge. Provide balanced, well-researched responses for international users." customParameters: max_tool_calls: 5 - temperature: 0.4 max_cost_per_session: 0.50 # Simple 1:1 segment-to-variation mapping diff --git a/bootstrap/create_configs.py b/bootstrap/create_configs.py index b64f92d..accc183 100644 --- a/bootstrap/create_configs.py +++ b/bootstrap/create_configs.py @@ -7,80 +7,106 @@ import os import yaml import requests -import json import time from pathlib import Path from dotenv import load_dotenv +from requests.adapters import HTTPAdapter +from urllib3.util.retry import Retry + +# The LaunchDarkly API rate-limits bursts of writes; wait and retry instead of skipping the call. +http = requests.Session() +http.mount("https://", HTTPAdapter(max_retries=Retry( + total=5, backoff_factor=2, status_forcelist=[429], allowed_methods=None, raise_on_status=False))) + +# JSON schemas for the tools in ai_config_manifest.yaml, matching the tutorials +TOOL_SCHEMAS = { + "search_v1": { + "type": "object", + "properties": { + "query": {"description": "Search query for keyword matching", "type": "string"}, + "top_k": {"description": "Number of results to return", "type": "number"} + }, + "additionalProperties": False, + "required": ["query"] + }, + "search_v2": { + "type": "object", + "properties": { + "query": {"description": "Search query for semantic matching", "type": "string"}, + "top_k": {"description": "Number of results to return", "type": "number"} + }, + "additionalProperties": False, + "required": ["query"] + }, + "reranking": { + "type": "object", + "properties": { + "query": {"description": "Original query for scoring", "type": "string"}, + "results": {"description": "Results to rerank", "type": "array"} + }, + "additionalProperties": False, + "required": ["query", "results"] + }, + "arxiv_search": { + "type": "object", + "properties": { + "query": {"description": "Search query for academic papers", "type": "string"}, + "max_results": {"description": "Maximum number of papers to return", "type": "number"} + }, + "additionalProperties": False, + "required": ["query"] + }, + "openalex_search": { + "type": "object", + "properties": { + "query": {"description": "Search query for scholarly works", "type": "string"} + }, + "additionalProperties": False, + "required": ["query"] + }, +} class MultiAgentBootstrap: def __init__(self, api_key, base_url="https://app.launchdarkly.com"): self.api_key = api_key self.base_url = base_url - self.overwrite = False self.headers = { "Authorization": api_key, - "LD-API-Version": "beta", + "LD-API-Version": "beta", "Content-Type": "application/json" } - + def create_segment(self, project_key, segment_data): """Create user segment for targeting using two-step process""" url = f"{self.base_url}/api/v2/segments/{project_key}/production" - + # Step 1: Create empty segment (LaunchDarkly ignores rules in POST) payload = { "key": segment_data["key"], "name": segment_data["key"].replace("-", " ").title() } - - response = requests.post(url, headers=self.headers, json=payload, timeout=30) - + + response = http.post(url, headers=self.headers, json=payload, timeout=30) + if response.status_code in [200, 201]: - print(f" Empty segment '{segment_data['key']}' created") + print(f"βœ… Empty segment '{segment_data['key']}' created") time.sleep(0.5) - - # Step 2: Add rules via semantic patch - return self.add_segment_rules(project_key, segment_data) - elif response.status_code == 409: - if self.overwrite: - print(f" Segment '{segment_data['key']}' already exists, deleting and recreating...") - # Delete existing segment - delete_url = f"{self.base_url}/api/v2/segments/{project_key}/production/{segment_data['key']}" - delete_response = requests.delete(delete_url, headers=self.headers, timeout=30) - - if delete_response.status_code == 204: - print(f"πŸ—‘οΈ Deleted existing segment '{segment_data['key']}'") - time.sleep(1) # Wait for deletion to propagate - # Retry creation - retry_response = requests.post(url, headers=self.headers, json=payload, timeout=30) - if retry_response.status_code in [200, 201]: - print(f" Empty segment '{segment_data['key']}' recreated") - time.sleep(0.5) - # Step 2: Add rules via semantic patch - return self.add_segment_rules(project_key, segment_data) - else: - print(f" Failed to recreate segment: {retry_response.text}") - return None - else: - print(f" Failed to delete existing segment: {delete_response.text}") - return None - else: - print(f" Segment '{segment_data['key']}' already exists, adding rules...") - return self.add_segment_rules(project_key, segment_data) + print(f"⚠️ Segment '{segment_data['key']}' already exists, adding rules...") else: - print(f" Failed to create segment: {response.text}") + print(f"❌ Failed to create segment: {response.text}") return None - + + # Step 2: Add rules via semantic patch + return self.add_segment_rules(project_key, segment_data) + def add_segment_rules(self, project_key, segment_data): """Add rules to existing segment using semantic patch""" segment_key = segment_data["key"] url = f"{self.base_url}/api/v2/segments/{project_key}/production/{segment_key}" - - # Build instructions for semantic patch - instructions = [] - + # Each segment should have one rule with multiple clauses + instructions = [] if segment_data.get("rules"): clauses = [] for clause in segment_data["rules"]: @@ -91,127 +117,67 @@ def add_segment_rules(self, project_key, segment_data): "contextKind": clause["contextKind"], "negate": clause["negate"] }) - + instructions.append({ "kind": "addRule", "clauses": clauses }) - + payload = { "environmentKey": "production", "instructions": instructions } - - print(f" Adding {len(instructions)} rules to segment '{segment_key}'") - + + print(f" πŸ”§ Adding {len(instructions)} rules to segment '{segment_key}'") + # Use semantic patch headers for segment rule updates patch_headers = self.headers.copy() patch_headers["Content-Type"] = "application/json; domain-model=launchdarkly.semanticpatch" - - response = requests.patch(url, headers=patch_headers, json=payload, timeout=30) - + + response = http.patch(url, headers=patch_headers, json=payload, timeout=30) + if response.status_code == 200: result = response.json() rules_count = len(result.get("rules", [])) - print(f" Rules added to segment '{segment_key}' (final count: {rules_count})") + print(f" βœ… Rules added to segment '{segment_key}' (final count: {rules_count})") time.sleep(0.5) return result else: - print(f" Failed to add rules to segment '{segment_key}': {response.text}") - return None - - def create_ai_config(self, project_key, config_data): - """Add variations to existing AI Config or create if not exists""" - config_key = config_data['key'] - - # Check if config already exists - check_url = f"{self.base_url}/api/v2/projects/{project_key}/ai-configs/{config_key}" - check_response = requests.get(check_url, headers=self.headers, timeout=30) - - if check_response.status_code == 200: - print(f" AI Config '{config_key}' exists, adding variations") - config_exists = True - else: - print(f" AI Config '{config_key}' not found, skipping creation") + print(f" ❌ Failed to add rules to segment '{segment_key}': {response.text}") return None - - # If overwrite mode, clear all targeting rules first to allow variation deletion/recreation - if self.overwrite: - print(f" πŸ”„ Overwrite mode: Clearing targeting rules for '{config_key}'...") - self.delete_all_targeting_rules(project_key, config_key) - - # Add variations to existing config - for variation in config_data["variations"]: - self.create_variation(project_key, config_key, variation) - - # Set up targeting (always update, regardless of overwrite mode) - if "targeting" in config_data: - self.update_targeting(project_key, config_key, config_data["targeting"]) - - return {"key": config_key, "status": "updated"} - - def delete_variation_if_exists(self, project_key, config_key, variation_key): - """Delete a specific variation if it exists""" - variations = self.list_variations(project_key, config_key) - # Debug: Show all available variation keys - available_keys = [v.get("key") or v.get("variationKey", "unknown") for v in variations] - print(f" Debug: Looking for '{variation_key}' in available variations: {available_keys}") - - # Find the variation by key - variation_id = None - for variation in variations: - v_key = variation.get("key") or variation.get("variationKey") - if v_key == variation_key: - variation_id = variation.get("_id") or variation.get("id") - break - - if not variation_id: - print(f" ℹ️ Variation '{variation_key}' not found in AI config") - return False - - # Delete the variation - delete_url = f"{self.base_url}/api/v2/projects/{project_key}/ai-configs/{config_key}/variations/{variation_id}" - delete_response = requests.delete(delete_url, headers=self.headers, timeout=30) - - if delete_response.status_code == 204: - print(f" πŸ—‘οΈ Deleted existing variation '{variation_key}'") - time.sleep(0.5) # Rate limiting delay - return True - else: - print(f" Failed to delete variation '{variation_key}': {delete_response.status_code}") - return False - + def create_variation(self, project_key, config_key, variation_data): """Create AI Config variation""" - variation_key = variation_data["key"] - - # If overwrite mode, delete existing variation first - if self.overwrite: - self.delete_variation_if_exists(project_key, config_key, variation_key) - url = f"{self.base_url}/api/v2/projects/{project_key}/ai-configs/{config_key}/variations" - - # Map model IDs to correct modelConfigKey values + model_config = variation_data["modelConfig"] model_id = model_config["modelId"] - provider = model_config["provider"].lower() - - # Map to correct LaunchDarkly model config keys + + # Map to correct LaunchDarkly model config keys and canonical provider names model_config_key_map = { - "claude-sonnet-4-6": "Anthropic.claude-sonnet-4-6", - "claude-haiku-4-5-20251001": "Anthropic.claude-haiku-4-5-20251001", - "claude-opus-4-7": "Anthropic.claude-opus-4-7", - "gpt-4o": "OpenAI.gpt-4o", - "gpt-4o-mini": "OpenAI.gpt-4o-mini-2024-07-18", + "claude-sonnet-5-5": "Anthropic.claude-sonnet-5-5", + "claude-haiku-5-5": "Anthropic.claude-haiku-5-5", + "claude-opus-5-5": "Anthropic.claude-opus-5-5", + "gpt-6.2-sol": "OpenAI.gpt-6.2-sol", + "gpt-6.1-terra": "OpenAI.gpt-6.1-terra", + "gpt-6-luna": "OpenAI.gpt-6-luna", "mistral-small-latest": "Mistral.mistral-small-latest" } - + provider_name_map = { + "anthropic": "Anthropic", + "bedrock": "Bedrock", + "cohere": "Cohere", + "deepseek": "DeepSeek", + "gemini": "Gemini", + "google": "Google", + "meta": "Meta", + "mistral": "Mistral", + "openai": "OpenAI", + "perplexity": "Perplexity", + "xai": "xAI", + } model_config_key = model_config_key_map.get(model_id) - if not model_config_key: - print(f" Unknown model ID '{model_id}', using fallback approach") - # Fallback to original approach - model_config_key = None - + payload = { "key": variation_data["key"], "name": variation_data.get("name", variation_data["key"].replace("-", " ").title()), @@ -219,181 +185,43 @@ def create_variation(self, project_key, config_key, variation_data): "instructions": variation_data["instructions"], "tools": [{"key": tool, "version": 1} for tool in variation_data.get("tools", [])] } - + + # Custom parameters such as max_tool_calls live in the variation's model.custom + if variation_data.get("customParameters"): + payload["model"] = {"custom": variation_data["customParameters"]} + # Use modelConfigKey if we have it, otherwise fallback to modelName/provider if model_config_key: payload["modelConfigKey"] = model_config_key - print(f" Using modelConfigKey: {model_config_key}") + print(f" πŸ”§ Using modelConfigKey: {model_config_key}") else: + raw_provider = model_config["provider"] + provider_name = provider_name_map.get(raw_provider.lower(), raw_provider) payload["modelName"] = model_id - payload["provider"] = {"name": model_config["provider"].title()} - print(f" Using modelName/provider fallback: {model_id}/{provider}") - - print(f"DEBUG: Sending payload: {json.dumps(payload, indent=2)}") - response = requests.post(url, headers=self.headers, json=payload, timeout=30) - + payload["provider"] = {"name": provider_name} + print(f" πŸ”§ Using modelName/provider fallback: {model_id}/{provider_name}") + + response = http.post(url, headers=self.headers, json=payload, timeout=30) + if response.status_code in [200, 201]: - print(f" Variation '{variation_data['key']}' created") + print(f" βœ… Variation '{variation_data['key']}' created") time.sleep(0.5) return response.json() elif response.status_code == 409: - if self.overwrite: - return self.update_variation(project_key, config_key, variation_data) - else: - return None - else: - print(f" Failed to create variation: {response.text}") + # Already exists; this script is add-only return None - - def update_variation(self, project_key, config_key, variation_data): - """Update existing AI Config variation using variations endpoint IDs.""" - variation_key = variation_data["key"] - variations = self.list_variations(project_key, config_key) - variation_id = None - for variation in variations: - v_key = variation.get("key") or variation.get("variationKey") - if v_key == variation_key: - variation_id = variation.get("_id") or variation.get("id") - break - - if not variation_id: - print(f" Could not resolve variation ID for '{variation_key}' via variations endpoint") - return None - - # Use the AI config variation ID with the regular AI config variations endpoint - url = f"{self.base_url}/api/v2/projects/{project_key}/ai-configs/{config_key}/variations/{variation_id}" - - # Build the same payload as create with model config key mapping - model_config = variation_data["modelConfig"] - model_id = model_config["modelId"] - - # Map to correct LaunchDarkly model config keys - model_config_key_map = { - "claude-sonnet-4-6": "Anthropic.claude-sonnet-4-6", - "claude-haiku-4-5-20251001": "Anthropic.claude-haiku-4-5-20251001", - "claude-opus-4-7": "Anthropic.claude-opus-4-7", - "gpt-4o": "OpenAI.gpt-4o", - "gpt-4o-mini": "OpenAI.gpt-4o-mini-2024-07-18", - "mistral-small-latest": "Mistral.mistral-small-latest" - } - - model_config_key = model_config_key_map.get(model_id) - - payload = { - "instructions": variation_data["instructions"], - "tools": [{"key": tool, "version": 1} for tool in variation_data.get("tools", [])] - } - - # Use modelConfigKey if we have it, otherwise fallback to modelName/provider - if model_config_key: - payload["modelConfigKey"] = model_config_key - print(f" Updating with modelConfigKey: {model_config_key}") else: - payload["modelName"] = model_id - payload["provider"] = {"name": model_config["provider"].title()} - print(f" Updating with modelName/provider fallback: {model_id}") - - response = requests.patch(url, headers=self.headers, json=payload, timeout=30) - - if response.status_code == 200: - print(f" Variation '{variation_data['key']}' updated") - time.sleep(0.5) - return response.json() - else: - print(f" Failed to update variation: {response.text}") + print(f" ❌ Failed to create variation: {response.text}") return None - + def create_tool(self, project_key, tool_data): """Create tool for AI Configs using correct API endpoint""" - tool_key = tool_data["key"] - - # Note: Tool deletion is handled in the main cleanup flow due to dependencies - # Tools can't be deleted while variations still reference them - url = f"{self.base_url}/api/v2/projects/{project_key}/ai-tools" - - # Build schema per tool key based on tutorial_2.md and README - schema = {"type": "object", "properties": {}, "required": [], "additionalProperties": False} - if tool_key == "search_v1": - schema = { - "type": "object", - "properties": { - "query": { - "description": "Search query for keyword matching", - "type": "string" - }, - "top_k": { - "description": "Number of results to return", - "type": "number" - } - }, - "additionalProperties": False, - "required": ["query"] - } - elif tool_key == "search_v2": - schema = { - "type": "object", - "properties": { - "query": { - "description": "Search query for semantic matching", - "type": "string" - }, - "top_k": { - "description": "Number of results to return", - "type": "number" - } - }, - "additionalProperties": False, - "required": ["query"] - } - elif tool_key == "reranking": - schema = { - "type": "object", - "properties": { - "query": { - "description": "Original query for scoring", - "type": "string" - }, - "results": { - "description": "Results to rerank", - "type": "array" - } - }, - "additionalProperties": False, - "required": ["query", "results"] - } - elif tool_key == "arxiv_search": - schema = { - "type": "object", - "properties": { - "query": { - "description": "Search query for academic papers", - "type": "string" - }, - "max_results": { - "description": "Maximum number of papers to return", - "type": "number" - } - }, - "additionalProperties": False, - "required": ["query"] - } - elif tool_key == "semantic_scholar": - schema = { - "type": "object", - "properties": { - "query": { - "description": "Search query for citation data", - "type": "string" - }, - "fields": { - "description": "Fields to return from papers", - "type": "array" - } - }, - "additionalProperties": False, - "required": ["query"] - } + + schema = TOOL_SCHEMAS.get( + tool_data["key"], + {"type": "object", "properties": {}, "required": [], "additionalProperties": False} + ) payload = { "key": tool_data["key"], @@ -401,244 +229,89 @@ def create_tool(self, project_key, tool_data): "description": tool_data["description"], "schema": schema } - + # Add MCP-specific configuration if applicable if tool_data.get("type") == "mcp": payload["mcpServer"] = tool_data.get("server", "") - # MCP tools may have different schema requirements payload["type"] = "mcp" else: payload["type"] = "function" - - print(f" Creating tool with payload: {json.dumps(payload, indent=2)}") - response = requests.post(url, headers=self.headers, json=payload, timeout=30) - + + response = http.post(url, headers=self.headers, json=payload, timeout=30) + if response.status_code in [200, 201]: - print(f" Tool '{tool_data['key']}' created") + print(f" βœ… Tool '{tool_data['key']}' created") time.sleep(0.5) return response.json() elif response.status_code == 409: return None else: - print(f" Failed to create tool: {response.text}") - try: - error_detail = response.json() - print(f" Error details: {json.dumps(error_detail, indent=2)}") - except: - pass + print(f" ❌ Failed to create tool: {response.text}") return None - def delete_tool(self, project_key, tool_key): - """Delete tool from project""" - url = f"{self.base_url}/api/v2/projects/{project_key}/ai-tools/{tool_key}" - - response = requests.delete(url, headers=self.headers, timeout=30) - - if response.status_code == 204: - print(f" πŸ—‘οΈ Tool '{tool_key}' deleted") - time.sleep(0.5) - return True - elif response.status_code == 404: - print(f" ℹ️ Tool '{tool_key}' not found (may already be deleted)") - return True - else: - print(f" Failed to delete tool '{tool_key}': {response.text}") - return False - - def delete_all_targeting_rules(self, project_key, config_key): - """Clear all targeting rules by setting everything to 'disabled' variation""" - url = f"{self.base_url}/api/v2/projects/{project_key}/ai-configs/{config_key}/targeting" - - # Get current targeting to understand existing rules and find disabled variation - response = requests.get(url, headers=self.headers, timeout=30) - if response.status_code != 200: - print(f" Could not fetch targeting for '{config_key}'") - return False - - targeting_data = response.json() - rules = targeting_data.get("rules", []) - variations = targeting_data.get("variations", []) - - # Debug: Print current targeting state - print(f" Debug: '{config_key}' has {len(rules)} rules and {len(variations)} variations") - if rules: - rule_info = [f'rule-{i}: segments={rule.get("clauses", [])}' for i, rule in enumerate(rules)] - print(f" Rules: {rule_info}") - - # Find the "disabled" variation ID - disabled_variation_id = None - for variation in variations: - if variation.get("name") == "disabled": - disabled_variation_id = variation["_id"] - break - - if not disabled_variation_id: - print(f" Could not find 'disabled' variation for '{config_key}'") - print(f" Available variations: {[v.get('name', 'unknown') for v in variations]}") - return False - - if not rules: - print(f" ℹ️ No targeting rules to clear for '{config_key}'") - return True - - # Create instructions to remove all rules and set fallthrough to disabled - instructions = [] - - # Remove all existing rules - for rule in rules: - instructions.append({ - "kind": "removeRule", - "ruleId": rule["_id"] - }) - - # Set fallthrough to disabled variation - instructions.append({ - "kind": "updateFallthroughVariationOrRollout", - "variationId": disabled_variation_id - }) - - payload = { - "environmentKey": "production", - "instructions": instructions - } - - print(f" Debug: Sending {len(instructions)} instructions to clear targeting") - response = requests.patch(url, headers=self.headers, json=payload, timeout=30) - - if response.status_code == 200: - print(f" πŸ—‘οΈ Cleared {len(rules)} targeting rules for '{config_key}' (set to disabled)") - time.sleep(0.5) - return True - else: - print(f" Failed to clear targeting rules: {response.text}") - return False - def get_targeting_variation_map(self, project_key, config_key): """Get targeting variation IDs (different from AI config variation IDs)""" url = f"{self.base_url}/api/v2/projects/{project_key}/ai-configs/{config_key}/targeting" - response = requests.get(url, headers=self.headers, timeout=30) - - if response.status_code == 200: - targeting_data = response.json() - targeting_variations = targeting_data.get("variations", []) - - variation_map = {} - for variation in targeting_variations: - # Skip the "disabled" variation - if variation.get("name") == "disabled": - continue - - # Extract variation key from the value._ldMeta.variationKey field - variation_value = variation.get("value", {}) - ld_meta = variation_value.get("_ldMeta", {}) - variation_key = ld_meta.get("variationKey") - - if variation_key: - variation_map[variation_key] = variation["_id"] - - return variation_map - else: - print(f" Failed to fetch targeting data: {response.text}") - return {} - - def get_ai_config_variation_id_map(self, project_key, config_key): - """Get AI config variation IDs from the AI config itself (key -> _id).""" - url = f"{self.base_url}/api/v2/projects/{project_key}/ai-configs/{config_key}" - response = requests.get(url, headers=self.headers, timeout=30) + response = http.get(url, headers=self.headers, timeout=30) if response.status_code != 200: - print(f" Failed to fetch AI config variations for '{config_key}': {response.text}") + print(f"❌ Failed to fetch targeting data: {response.text}") return {} - config_data = response.json() - variations = config_data.get("variations", []) - return {v.get("key"): v.get("_id") for v in variations if v.get("key") and v.get("_id")} + variation_map = {} + for variation in response.json().get("variations", []): + # Skip the "disabled" variation + if variation.get("name") == "disabled": + continue - def list_variations(self, project_key, config_key): - """List variations via the variations endpoint used for create/update/delete.""" - url = f"{self.base_url}/api/v2/projects/{project_key}/ai-configs/{config_key}/variations" - response = requests.get(url, headers=self.headers, timeout=30) - if response.status_code != 200: - print(f" Could not list variations for '{config_key}': {response.text}") - return [] - try: - data = response.json() - except Exception: - print(" Invalid JSON from variations list") - return [] - if isinstance(data, list): - return data - if isinstance(data, dict) and isinstance(data.get("items"), list): - return data["items"] - return [] - - def update_variation_tools_only(self, project_key, config_key, variation_key, tools_list): - """Update only the tools array for a specific variation (by key).""" - variation_id_map = self.get_ai_config_variation_id_map(project_key, config_key) - variation_id = variation_id_map.get(variation_key) - if not variation_id: - print(f" Could not find variation id for '{variation_key}' while updating tools") - return False - - url = f"{self.base_url}/api/v2/projects/{project_key}/ai-configs/{config_key}/variations/{variation_id}" - payload = { - "tools": [{"key": t, "version": 1} for t in (tools_list or [])] - } + # Extract variation key from the value._ldMeta.variationKey field + variation_key = variation.get("value", {}).get("_ldMeta", {}).get("variationKey") + if variation_key: + variation_map[variation_key] = variation["_id"] - response = requests.patch(url, headers=self.headers, json=payload, timeout=30) - if response.status_code == 200: - print(f" Updated tools for variation '{variation_key}' β†’ {tools_list or []}") - time.sleep(0.2) - return True - else: - print(f" Failed updating tools for '{variation_key}': {response.text}") - return False + return variation_map def ensure_ai_config_exists(self, project_key, config_data): - """Ensure an AI Config exists; do not delete it in overwrite mode.""" + """Check that an AI Config exists. Part 1 creates them, so this script never does.""" config_key = config_data["key"] url = f"{self.base_url}/api/v2/projects/{project_key}/ai-configs/{config_key}" - response = requests.get(url, headers=self.headers, timeout=30) + response = http.get(url, headers=self.headers, timeout=30) if response.status_code == 200: - print(f" AI Config '{config_key}' exists") + print(f"βœ… AI Config '{config_key}' exists") return True - else: - # For safety, we won't attempt to create brand-new configs here without a stable schema. - print(f" AI Config '{config_key}' not found. Skipping creation.") - return False - - # Removed detachment logic per new overwrite deletion order requirements + print(f"⚠️ AI Config '{config_key}' not found. Skipping creation.") + return False def update_targeting(self, project_key, config_key, targeting_data): """Update AI Config targeting rules using correct agent mode format""" # First get the targeting variation IDs targeting_variation_map = self.get_targeting_variation_map(project_key, config_key) if not targeting_variation_map: - print(f" Could not get targeting variation map for '{config_key}'") + print(f"❌ Could not get targeting variation map for '{config_key}'") return None - - print(f" Available targeting variations for '{config_key}': {list(targeting_variation_map.keys())}") - + + print(f"πŸ“Š Available targeting variations for '{config_key}': {list(targeting_variation_map.keys())}") + url = f"{self.base_url}/api/v2/projects/{project_key}/ai-configs/{config_key}/targeting" - + instructions = [] - + # Add segment-based rules for rule in targeting_data["rules"]: variation_key = rule["variation"] targeting_variation_id = targeting_variation_map.get(variation_key) - + if not targeting_variation_id: - print(f" Variation '{variation_key}' not found in targeting variations") + print(f"⚠️ Variation '{variation_key}' not found in targeting variations") continue - + # Create add rule instruction for each segment for segment in rule["segments"]: instruction = { "kind": "addRule", "clauses": [ { - "attribute": "segmentMatch", + "attribute": "segmentMatch", "op": "segmentMatch", "values": [segment], "contextKind": "user" @@ -647,82 +320,73 @@ def update_targeting(self, project_key, config_key, targeting_data): "variationId": targeting_variation_id } instructions.append(instruction) - print(f" Added rule: segment '{segment}' -> variation '{variation_key}'") - + print(f" βœ… Added rule: segment '{segment}' -> variation '{variation_key}'") + # Set fallthrough variation fallthrough_variation_key = targeting_data["defaultVariation"] fallthrough_variation_id = targeting_variation_map.get(fallthrough_variation_key) - + if fallthrough_variation_id: instructions.append({ "kind": "updateFallthroughVariationOrRollout", "variationId": fallthrough_variation_id }) - print(f" Set fallthrough to variation '{fallthrough_variation_key}'") + print(f" βœ… Set fallthrough to variation '{fallthrough_variation_key}'") else: - print(f" Fallthrough variation '{fallthrough_variation_key}' not found") - + print(f"⚠️ Fallthrough variation '{fallthrough_variation_key}' not found") + payload = { "environmentKey": "production", "instructions": instructions } - - response = requests.patch(url, headers=self.headers, json=payload, timeout=30) - + + response = http.patch(url, headers=self.headers, json=payload, timeout=30) + if response.status_code == 200: - print(f" Targeting rules updated for '{config_key}'") + print(f"βœ… Targeting rules updated for '{config_key}'") return response.json() else: - print(f" Failed to update targeting: {response.text}") + print(f"❌ Failed to update targeting: {response.text}") return None def main(): load_dotenv() - - print(" LaunchDarkly AI Config Bootstrap") + + print("πŸš€ LaunchDarkly AI Config Bootstrap") print("=" * 50) - print(" IMPORTANT: This script is for INITIAL SETUP ONLY") - print(" After bootstrap completes:") + print("⚠️ IMPORTANT: This script is for INITIAL SETUP ONLY") + print("πŸ“ After bootstrap completes:") print(" β€’ Make ALL configuration changes in LaunchDarkly UI") print(" β€’ Do NOT modify ai_config_manifest.yaml") print(" β€’ LaunchDarkly is your single source of truth") print("=" * 50) print() - + api_key = os.getenv("LD_API_KEY") if not api_key: - print(" LD_API_KEY environment variable not set") + print("❌ LD_API_KEY environment variable not set") print(" Get your API key from: https://app.launchdarkly.com/settings/authorization") return - + # Load manifest manifest_path = Path(__file__).parent / "ai_config_manifest.yaml" - if not manifest_path.exists(): - print(" ai_config_manifest.yaml not found") - print(" Make sure you're running this from the bootstrap/ directory") - return - with open(manifest_path) as f: manifest = yaml.safe_load(f) - - project_key = manifest["project"]["key"] + + project_key = os.getenv("LD_PROJECT_KEY") or manifest["project"]["key"] bootstrap = MultiAgentBootstrap(api_key) - - print(" Starting multi-agent system bootstrap (add-only)...") + + print("πŸš€ Starting multi-agent system bootstrap (add-only)...") print(f"πŸ“¦ Project: {project_key}") print() - print("πŸ“‹ Creation order: tools β†’ ai configs β†’ variations β†’ segments β†’ targeting") - print() - # 1) Tools - if "tool" in manifest["project"]: - print(" Creating tools...") - part1_tool_keys = {"search_v2", "reranking"} - for tool in manifest["project"]["tool"]: - if tool.get("key") in part1_tool_keys: - continue + # 1) Tools (search_v2 and reranking were created in Part 1) + print("πŸ”§ Creating tools...") + part1_tool_keys = {"search_v2", "reranking"} + for tool in manifest["project"]["tool"]: + if tool["key"] not in part1_tool_keys: bootstrap.create_tool(project_key, tool) - print() + print() # 2) AI Configs (ensure they exist from Part 1) print("πŸ€– Ensuring AI configs exist...") @@ -731,44 +395,41 @@ def main(): if bootstrap.ensure_ai_config_exists(project_key, ai_config): existing_config_keys.add(ai_config["key"]) if not existing_config_keys: - print(" No existing AI configs found. This script assumes Part 1 created base configs. Skipping variations/targeting.") + print("⚠️ No existing AI configs found. This script assumes Part 1 created base configs. Skipping variations/targeting.") print() # 3) Variations (add-only; skip if exists) print("🧩 Creating variations...") skip_variations = {"supervisor-basic"} # Created in Part 1 for ai_config in manifest["project"]["ai_config"]: - config_key = ai_config["key"] - if config_key not in existing_config_keys: + if ai_config["key"] not in existing_config_keys: continue for variation in ai_config.get("variations", []): - if variation.get("key") in skip_variations: - continue - bootstrap.create_variation(project_key, config_key, variation) + if variation["key"] not in skip_variations: + bootstrap.create_variation(project_key, ai_config["key"], variation) print() # 4) Segments (required for targeting rules) - if "segment" in manifest["project"]: - print("πŸ“¦ Creating segments (for targeting rules)...") - for segment in manifest["project"]["segment"]: - bootstrap.create_segment(project_key, segment) - print() - - # 5) Targeting (idempotent updates; skip duplicate rules) - print(" Updating targeting rules...") + print("πŸ“¦ Creating segments (for targeting rules)...") + for segment in manifest["project"]["segment"]: + bootstrap.create_segment(project_key, segment) + print() + + # 5) Targeting + print("🎯 Updating targeting rules...") for ai_config in manifest["project"]["ai_config"]: config_key = ai_config["key"] if config_key not in existing_config_keys: continue - if "targeting" in ai_config and ai_config["targeting"].get("rules"): + if ai_config["targeting"].get("rules"): bootstrap.update_targeting(project_key, config_key, ai_config["targeting"]) - elif "targeting" in ai_config and not ai_config["targeting"].get("rules"): + else: print(f" ⏭️ Skipping targeting for '{config_key}' (empty rules)") print() print("✨ Bootstrap complete!") print() - print(" Next steps:") + print("🎯 Next steps:") print(" 1. Check your LaunchDarkly dashboard to verify configurations") print(" 2. Test different user contexts with the demo") print(" 3. Monitor usage patterns and adjust targeting rules") @@ -780,4 +441,4 @@ def main(): print(" β€’ This YAML file is now a historical record") if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/bootstrap/tutorial_3_experiment_variations.py b/bootstrap/tutorial_3_experiment_variations.py index cb672bf..fc3c51b 100644 --- a/bootstrap/tutorial_3_experiment_variations.py +++ b/bootstrap/tutorial_3_experiment_variations.py @@ -3,7 +3,7 @@ Bootstrap script for Tutorial 3 Experiment Variations Creates the experiment variation needed for tutorial-3 A/B testing: -- Premium Model Value Analysis: Does Claude Opus 4 deliver superior user satisfaction compared to GPT-4o for premium users? +- Premium Model Value Analysis: Does Claude Opus 5.5 deliver superior user satisfaction compared to GPT-6.2 Sol for premium users? This script is separate from the tutorial-2 bootstrap and only handles experiment variations, not the base AI Configs (which should already exist). @@ -23,7 +23,7 @@ class Tutorial3VariationBootstrap: def __init__(self): self.api_key = os.getenv('LD_API_KEY') - self.project_key = "multi-agent-chatbot" + self.project_key = os.getenv("LD_PROJECT_KEY") or "multi-agent-chatbot" self.base_url = "https://app.launchdarkly.com/api/v2" if not self.api_key: @@ -37,48 +37,19 @@ def __init__(self): "LD-API-Version": "beta" } - def verify_security_agent_variations(self) -> bool: - """Verify that existing security agent variations are available for experiments""" - - print("\nπŸ” Verifying security agent variations...") - - # Check if security-agent AI Config exists with required variations - url = f"{self.base_url}/projects/{self.project_key}/ai-configs/security-agent/variations" - response = requests.get(url, headers=self.headers) - - if response.status_code != 200: - print(f"❌ Error: security-agent variations not found (status: {response.status_code})") - print(f" Response: {response.text}") - print(" Please complete tutorial-2 first to create the base AI Configs") - return False - - variations = response.json().get("items", []) - variation_keys = [var["key"] for var in variations] - required_variations = ["baseline", "enhanced"] - - missing_variations = [var for var in required_variations if var not in variation_keys] - - if missing_variations: - print(f"❌ Error: Missing required security agent variations: {missing_variations}") - print(" Please ensure security-agent has baseline and enhanced variations") - return False - - print(" βœ… Security agent variations exist (baseline, enhanced)") - return True - def create_premium_model_variations(self) -> bool: """Create the 1 premium model variation for premium model experiment""" variations = [ { "key": "claude-opus-treatment", - "name": "Claude Opus 4 Treatment", + "name": "Claude Opus 5.5 Treatment", "instructions": "You are a helpful assistant that can search documentation and research papers. When search results are available, prioritize information from those results over your general knowledge to provide the most accurate and up-to-date responses. Use available tools to search the knowledge base and external research databases to answer questions accurately and comprehensively.", "model": { - "name": "claude-opus-4-7", + "name": "claude-opus-5-5", "provider": "anthropic" }, - "tools": ["search_v1", "search_v2", "reranking", "arxiv_search", "semantic_scholar"], + "tools": ["search_v1", "search_v2", "reranking", "arxiv_search", "openalex_search"], "customParameters": {"max_tool_calls": 10} } ] @@ -90,15 +61,35 @@ def _create_variations(self, ai_config_key: str, variations: List[Dict[str, Any] print(f"\nπŸ“ Creating {len(variations)} variations for {ai_config_key}...") + # Map model name to LaunchDarkly modelConfigKey and canonical provider names + model_config_key_map = { + "claude-opus-5-5": "Anthropic.claude-opus-5-5", + "claude-sonnet-5-5": "Anthropic.claude-sonnet-5-5", + "claude-haiku-5-5": "Anthropic.claude-haiku-5-5", + "gpt-6.2-sol": "OpenAI.gpt-6.2-sol", + "gpt-6.1-terra": "OpenAI.gpt-6.1-terra", + "gpt-6-luna": "OpenAI.gpt-6-luna", + "mistral-small-latest": "Mistral.mistral-small-latest", + } + provider_name_map = { + "anthropic": "Anthropic", + "bedrock": "Bedrock", + "cohere": "Cohere", + "deepseek": "DeepSeek", + "gemini": "Google", + "google": "Google", + "groq": "Groq", + "meta": "Meta", + "mistral": "Mistral", + "openai": "OpenAI", + "perplexity": "Perplexity", + "xai": "xAI", + } + for variation in variations: url = f"{self.base_url}/projects/{self.project_key}/ai-configs/{ai_config_key}/variations" - - # Map model name to LaunchDarkly modelConfigKey + model_name = variation["model"]["name"] - model_config_key_map = { - "claude-opus-4-7": "Anthropic.claude-opus-4-7", - } - model_config_key = model_config_key_map.get(model_name) payload = { @@ -108,50 +99,43 @@ def _create_variations(self, ai_config_key: str, variations: List[Dict[str, Any] "instructions": variation["instructions"], "tools": [{"key": tool, "version": 1} for tool in variation["tools"]], } - + # Use modelConfigKey if available, otherwise fallback to modelName/provider if model_config_key: payload["modelConfigKey"] = model_config_key print(f" Using modelConfigKey: {model_config_key}") else: + raw_provider = variation["model"]["provider"] + provider_name = provider_name_map.get(raw_provider.lower(), raw_provider) payload["modelName"] = model_name - payload["provider"] = {"name": variation["model"]["provider"]} - print(f" Using modelName/provider: {model_name}") - - # Add custom parameters if they exist - if variation["customParameters"]: - # Custom parameters should be in the payload root for AI Config variations - payload.update(variation["customParameters"]) - - try: - response = requests.post(url, json=payload, headers=self.headers) - - if response.status_code == 201: - print(f" βœ… Created variation: {variation['key']}") - elif response.status_code == 409: - print(f" ⚠️ Variation already exists: {variation['key']}, attempting to update...") - # Try to update the existing variation - get_url = f"{url}/{variation['key']}" - # Remove 'messages' field for PATCH (not supported in agent mode) - update_payload = {k: v for k, v in payload.items() if k != 'messages'} - update_response = requests.patch(get_url, json=update_payload, headers=self.headers) - if update_response.status_code == 200: - print(f" βœ… Updated variation: {variation['key']}") - else: - print(f" ❌ Failed to update {variation['key']}: {update_response.status_code}") - print(f" Response: {update_response.text}") + payload["provider"] = {"name": provider_name} + print(f" Using modelName/provider: {model_name}/{provider_name}") + + # Custom parameters such as max_tool_calls live in the variation's model.custom + payload["model"] = {"custom": variation["customParameters"]} + + response = requests.post(url, json=payload, headers=self.headers, timeout=30) + + if response.status_code == 201: + print(f" βœ… Created variation: {variation['key']}") + elif response.status_code == 409: + print(f" ⚠️ Variation already exists: {variation['key']}, attempting to update...") + # Remove 'messages' field for PATCH (not supported in agent mode) + update_payload = {k: v for k, v in payload.items() if k != 'messages'} + update_response = requests.patch(f"{url}/{variation['key']}", json=update_payload, headers=self.headers, timeout=30) + if update_response.status_code == 200: + print(f" βœ… Updated variation: {variation['key']}") else: - print(f" ❌ Failed to create {variation['key']}: {response.status_code}") - print(f" Response: {response.text}") - return False - - # Small delay to avoid rate limiting - time.sleep(0.5) - - except Exception as e: - print(f" ❌ Error creating {variation['key']}: {str(e)}") + print(f" ❌ Failed to update {variation['key']}: {update_response.status_code}") + print(f" Response: {update_response.text}") + else: + print(f" ❌ Failed to create {variation['key']}: {response.status_code}") + print(f" Response: {response.text}") return False + # Small delay to avoid rate limiting + time.sleep(0.5) + return True def verify_prerequisites(self) -> bool: @@ -161,7 +145,7 @@ def verify_prerequisites(self) -> bool: # Check if support-agent AI Config exists url = f"{self.base_url}/projects/{self.project_key}/ai-configs/support-agent" - response = requests.get(url, headers=self.headers) + response = requests.get(url, headers=self.headers, timeout=30) if response.status_code != 200: print(f"❌ Error: support-agent AI Config not found (status: {response.status_code})") @@ -172,9 +156,9 @@ def verify_prerequisites(self) -> bool: print(" βœ… support-agent AI Config exists") # Check if required tools exist - required_tools = ["search_v1", "search_v2", "reranking", "arxiv_search", "semantic_scholar"] - tools_url = f"{self.base_url}/projects/{self.project_key}/ai-configs/tools" - tools_response = requests.get(tools_url, headers=self.headers) + required_tools = ["search_v1", "search_v2", "reranking", "arxiv_search", "openalex_search"] + tools_url = f"{self.base_url}/projects/{self.project_key}/ai-tools" + tools_response = requests.get(tools_url, headers=self.headers, timeout=30) if tools_response.status_code == 200: existing_tools = [tool["key"] for tool in tools_response.json().get("items", [])] @@ -202,10 +186,6 @@ def run(self): print("\nπŸ“‹ Creating experiment variations...") - # Skip security agent verification - not needed for premium model experiment - print("\n⏭️ Skipping security agent verification (not required for premium model experiment)") - - # Create premium model variations if not self.create_premium_model_variations(): print("❌ Failed to create premium model variations") sys.exit(1) @@ -218,9 +198,9 @@ def run(self): print("3. Follow tutorial-3 for metrics and experiment setup") print("\nCreated variations:") print(" Premium Model: claude-opus-treatment") - print(" Security Agent: Uses existing baseline and enhanced variations") + print(" Security Agent: Uses existing basic-security and strict-security variations") print(" Note: Both experiments use existing other-paid configuration as control") if __name__ == "__main__": bootstrap = Tutorial3VariationBootstrap() - bootstrap.run() \ No newline at end of file + bootstrap.run() diff --git a/config_manager.py b/config_manager.py index a1976f0..6d58dcb 100644 --- a/config_manager.py +++ b/config_manager.py @@ -2,36 +2,172 @@ """ Simplified ConfigManager for LaunchDarkly AI Agent integration """ +import inspect import os -import time import json +import time +import uuid +from dataclasses import dataclass, field from pathlib import Path -import ldclient -from ldclient import Context -from ldai import LDAIClient, AIAgentConfigDefault, ModelConfig, ProviderConfig -from ldai.tracker import FeedbackKind +from typing import Any, Optional + +from launchdarkly_ai_server import ( + GraphNode, + SpanUsage, + create_handler, + execute_and_track, + get_client, + init_client, + inspect_config, + make_track_data, + parse_ai_config, + parse_template, + parse_usage, + set_input_content_attributes, + set_ld_span_attributes, + set_model_identity_attributes, + set_output_content_attributes, + set_tool_call_content_attributes, + set_usage_span_attributes, + shutdown, + text_message, + to_ld_context, +) +from opentelemetry import trace +from opentelemetry.trace import StatusCode as SpanStatusCode from dotenv import load_dotenv +from utils.cost_calculator import calculate_cost from utils.logger import log_student, log_debug import boto3 load_dotenv() +TRACER_NAME = "@launchdarkly/ai-langchain-agents" + +# How long to serve local defaults before trying to reach LaunchDarkly again +CLIENT_RETRY_SECONDS = 60 + +# The AI SDK has no feedback API, so these are sent as custom events. LaunchDarkly's +# built-in feedback metrics listen for these exact keys. +FEEDBACK_POSITIVE_EVENT = "$ld:ai:feedback:user:positive" +FEEDBACK_NEGATIVE_EVENT = "$ld:ai:feedback:user:negative" + +@dataclass +class ServedConfig: + """One resolved AgentControl config, from LaunchDarkly or from local defaults.""" + + key: str + config: dict[str, Any] + meta: dict[str, Any] = field(default_factory=dict) + from_fallback: bool = False + + @property + def instructions(self) -> str: + return self.config.get("instructions") or "" + + @property + def model_name(self) -> str: + return (self.config.get("model") or {}).get("name") or "unknown" + + @property + def provider_name(self) -> str: + return (self.config.get("provider") or {}).get("name") or "unknown" + + @property + def parameters(self) -> dict[str, Any]: + return (self.config.get("model") or {}).get("parameters") or {} + + @property + def custom(self) -> dict[str, Any]: + """Custom model params (e.g. max_tool_calls).""" + return (self.config.get("model") or {}).get("custom") or {} + + @property + def variation_key(self) -> str: + """The served variation. Local fallbacks have no variation, hence 'fallback'.""" + if self.from_fallback: + return "fallback" + return self.meta.get("variationKey") or "unknown" + + def render_instructions(self, variables: dict[str, Any] | None = None) -> str: + """Render Mustache placeholders (such as {{ldContext.plan}}) in instructions.""" + return parse_template(self.instructions, variables or {}) + + def track_data(self) -> dict[str, Any]: + """Metadata attached to custom metric events for experiment attribution.""" + meta = {"variationKey": "fallback", "version": 1} if self.from_fallback else self.meta + data = make_track_data(GraphNode(key=self.key, config=self.config, meta=meta), "", str(uuid.uuid4())) + data.pop("graphKey", None) + return data + + class FixedConfigManager: def __init__(self): - """Initialize LaunchDarkly client and AI client""" + """Initialize config defaults and the AWS session. + + The LaunchDarkly client is initialized lazily, because the current AI + SDK's init_client is async and this constructor is not. + """ self.sdk_key = os.getenv('LD_SDK_KEY') if not self.sdk_key: raise ValueError("LD_SDK_KEY environment variable is required") + self._client_retry_at = 0.0 # Load defaults from .ai_config_defaults.json self._load_config_defaults() - self._initialize_launchdarkly_client() - self._initialize_ai_client() - # Initialize AWS Bedrock session for SSO authentication self._initialize_bedrock_session() + async def _ensure_client(self) -> bool: + """Initialize the shared LaunchDarkly client. init_client is idempotent, so + this is safe to await on every request. + + Returns False if the client can't connect, so get_config serves the + local defaults. A failed connection takes up to 10 seconds, so after one + the local defaults are served for CLIENT_RETRY_SECONDS before retrying. + """ + if time.monotonic() < self._client_retry_at: + return False + try: + await init_client({"serviceName": os.getenv("LD_SERVICE_NAME", "multi-agent-chatbot")}) + return True + except RuntimeError as e: + self._client_retry_at = time.monotonic() + CLIENT_RETRY_SECONDS + log_student(f"CONFIG MANAGER: LaunchDarkly client unavailable, retrying in {CLIENT_RETRY_SECONDS}s: {e}") + return False + + def _initialize_bedrock_session(self): + """Initialize AWS Bedrock session if AUTH_METHOD=sso""" + auth_method = os.getenv('AUTH_METHOD', 'api-key').lower() + + if auth_method != 'sso': + self.boto3_session = None + log_debug("AUTH_METHOD not set to 'sso', Bedrock unavailable") + return + + aws_profile = os.getenv('AWS_PROFILE') + try: + # Use the profile if specified, otherwise the default credentials + self.aws_region = os.getenv('AWS_REGION', 'us-east-1') + self.boto3_session = boto3.Session(region_name=self.aws_region, profile_name=aws_profile) + log_debug(f"AWS: Using profile '{aws_profile or 'default'}' in region {self.aws_region}") + + # Test current SSO session + sts = self.boto3_session.client('sts') + identity = sts.get_caller_identity() + user_name = identity['Arn'].split('/')[-1] + account = identity['Account'] + log_student(f"AWS: Connected via SSO as {user_name} (Account: {account})") + + except Exception as e: + log_student(f"AWS SSO session not available: {e}") + + # Provide helpful login command with profile if specified + profile_hint = f" --profile {aws_profile}" if aws_profile else "" + log_student(f"Run: aws sso login{profile_hint}") + raise + def _load_config_defaults(self): """Load AI config defaults from .ai_config_defaults.json @@ -68,17 +204,41 @@ def _load_config_defaults(self): " ld-aic validate --config-keys 'supervisor-agent,support-agent,security-agent'" ) - def _get_default_config(self, config_key: str) -> AIAgentConfigDefault: - """Get fallback config from .ai_config_defaults.json + @staticmethod + def _normalize_tools(config_data: dict[str, Any], config_key: str) -> dict[str, Any]: + """Normalize a top-level `tools` list into LaunchDarkly's served config shape. + + ld-aic writes tools as a top-level list in `.ai_config_defaults.json`, whereas + LaunchDarkly serves `tools` as a `{key: spec}` dict alongside `model.parameters.tools`. + """ + tools = config_data.pop("tools", None) + if not isinstance(tools, list): + if tools is not None: + config_data["tools"] = tools + return config_data + + config_data["tools"] = { + t["name"]: {**t, "type": "function"} + for t in tools + if isinstance(t, dict) and "name" in t + } + model = config_data.setdefault("model", {}) + parameters = model.setdefault("parameters", {}) + parameters.setdefault("tools", tools) + log_debug( + f"DEFAULTS: normalized {len(tools)} tools for '{config_key}'" + ) + return config_data - Args: - config_key: The AI config key (e.g., 'support-agent') + def _get_default_config(self, config_key: str) -> dict[str, Any]: + """Get the fallback config for a key from .ai_config_defaults.json - Returns: - AIAgentConfigDefault object with config from the defaults file + The file is written in the same shape the SDK parses, so this strips the + `enabled` flag and validates the rest with the SDK's own parser rather + than trusting it. Raises: - ValueError: If config key not found in defaults + ValueError: If the key is missing, disabled, or fails validation. """ if config_key not in self.config_defaults: available_keys = list(self.config_defaults.keys()) @@ -87,105 +247,41 @@ def _get_default_config(self, config_key: str) -> AIAgentConfigDefault: f"Available configs: {', '.join(available_keys)}\n\n" "To add this config:\n" " 1. Create it in LaunchDarkly dashboard\n" - " 2. Run: ld-aic validate --config-keys '{config_key},...'\n" + f" 2. Run: ld-aic validate --config-keys '{config_key},...'\n" " 3. The config will be added to .ai_config_defaults.json" ) - config_data = self.config_defaults[config_key] - - # Convert JSON config to AIAgentConfigDefault - # Note: Tools are managed by LaunchDarkly and not part of defaults - return AIAgentConfigDefault( - enabled=config_data.get("enabled", True), - model=ModelConfig( - name=config_data["model"]["name"], - parameters=config_data["model"].get("parameters", {}) - ), - provider=ProviderConfig( - name=config_data["provider"]["name"] - ), - instructions=config_data.get("instructions", "You are a helpful assistant.") - ) - - def _initialize_launchdarkly_client(self): - """Initialize LaunchDarkly client""" - config = ldclient.Config(self.sdk_key) - ldclient.set_config(config) - self.ld_client = ldclient.get() - - max_wait = 10 - wait_time = 0 - while not self.ld_client.is_initialized() and wait_time < max_wait: - time.sleep(0.5) - wait_time += 0.5 - - if not self.ld_client.is_initialized(): - raise RuntimeError("LaunchDarkly client initialization failed") - - def _initialize_ai_client(self): - """Initialize AI client""" - self.ai_client = LDAIClient(self.ld_client) - - def _initialize_bedrock_session(self): - """Initialize AWS Bedrock session if AUTH_METHOD=sso""" - auth_method = os.getenv('AUTH_METHOD', 'api-key').lower() - - if auth_method != 'sso': - self.boto3_session = None - log_debug("AUTH_METHOD not set to 'sso', Bedrock unavailable") - return - - try: - # Initialize AWS session with optional profile support - aws_region = os.getenv('AWS_REGION', 'us-east-1') - aws_profile = os.getenv('AWS_PROFILE') - - # Create session with profile if specified, otherwise use default credentials - if aws_profile: - self.boto3_session = boto3.Session( - region_name=aws_region, - profile_name=aws_profile - ) - log_debug(f"AWS: Using profile '{aws_profile}' in region {aws_region}") - else: - self.boto3_session = boto3.Session(region_name=aws_region) - log_debug(f"AWS: Using default credentials in region {aws_region}") - - self.aws_region = aws_region - self.aws_profile = aws_profile + config_data = dict(self.config_defaults[config_key]) + config_data = self._normalize_tools(config_data, config_key) - # Test current SSO session - sts = self.boto3_session.client('sts') - identity = sts.get_caller_identity() - user_name = identity['Arn'].split('/')[-1] - account = identity['Account'] - log_student(f"AWS: Connected via SSO as {user_name} (Account: {account})") + if not config_data.pop("enabled", True): + raise ValueError( + f"❌ Fallback config '{config_key}' is marked disabled in " + ".ai_config_defaults.json, so there is nothing to serve." + ) - except Exception as e: - log_student(f"AWS SSO session not available: {e}") + result = parse_ai_config(config_data) + if not result.success: + raise ValueError( + f"❌ Fallback config '{config_key}' in .ai_config_defaults.json is " + f"not a valid AI config: {result.error.get('message')}\n\n" + "Regenerate it by running:\n" + f" ld-aic validate --config-keys '{config_key},...'" + ) - # Provide helpful login command with profile if specified - profile_hint = f" --profile {os.getenv('AWS_PROFILE')}" if os.getenv('AWS_PROFILE') else "" - log_student(f"Run: aws sso login{profile_hint}") - raise + return result.data - def build_context(self, user_id: str, user_context: dict = None) -> Context: + def build_context(self, user_id: str, user_context: dict = None) -> dict[str, Any]: """Build a LaunchDarkly context with consistent attributes. - + This ensures the same context is used for both AI Config evaluation and custom metric tracking, which is required for experiment association. """ - context_builder = Context.builder(user_id).kind('user') - - if user_context: - # Set all attributes from user_context for consistency - for key, value in user_context.items(): - context_builder.set(key, value) - log_debug(f"CONFIG MANAGER: Set {key}={value}") - - return context_builder.build() - - async def get_config(self, user_id: str, config_key: str = None, user_context: dict = None): + context = {"kind": "user", "key": user_id, **(user_context or {})} + log_debug(f"CONFIG MANAGER: Built LaunchDarkly context: {context}") + return context + + async def get_config(self, user_id: str, config_key: str, user_context: dict = None) -> ServedConfig: """Get LaunchDarkly AI Config with fallback to .ai_config_defaults.json Fallback chain: @@ -194,107 +290,165 @@ async def get_config(self, user_id: str, config_key: str = None, user_context: d 3. If config not in defaults file, raise helpful error """ log_debug(f"CONFIG MANAGER: Getting config for user_id={user_id}, config_key={config_key}") - log_debug(f"CONFIG MANAGER: User context: {user_context}") - # Build context using centralized method + client_ready = await self._ensure_client() ld_user_context = self.build_context(user_id, user_context) - log_debug(f"CONFIG MANAGER: Built LaunchDarkly context: {ld_user_context}") - - ai_config_key = config_key or os.getenv('LAUNCHDARKLY_AI_CONFIG_KEY', 'support-agent') - log_debug(f"CONFIG MANAGER: Using AI config key: {ai_config_key}") - # Load default from .ai_config_defaults.json (fails with helpful error if not found) - default_config = self._get_default_config(ai_config_key) - log_debug(f"CONFIG MANAGER: Loaded fallback default - model: {default_config.model.name}") - - # Call LaunchDarkly - SDK automatically falls back to default if LD unavailable - result = self.ai_client.agent_config( - ai_config_key, - ld_user_context, - default=default_config, # Use validated production defaults from file + inspected = ( + await inspect_config(config_key, ld_user_context) + if client_ready + else {"enabled": False, "config": None, "meta": None} ) - log_debug("CONFIG MANAGER: βœ… Got config (from LaunchDarkly or fallback)") - - # Debug the actual configuration received (basic info only) - try: - config_dict = result.to_dict() - log_debug(f"CONFIG MANAGER: Model: {config_dict.get('model', {}).get('name', 'unknown')}") - tracker = result.create_tracker() - if hasattr(tracker, '_variation_key'): - log_debug(f"CONFIG MANAGER: Variation: {tracker._variation_key}") - except Exception as debug_e: - log_debug(f"CONFIG MANAGER: Could not debug result: {debug_e}") - return result - + if inspected["enabled"] and inspected["config"]: + served = ServedConfig( + key=config_key, + config=inspected["config"], + meta=inspected["meta"] or {}, + ) + log_debug(f"CONFIG MANAGER: βœ… Got config from LaunchDarkly: {served.model_name} ({served.variation_key})") + return served - def clear_cache(self): - """Clear LaunchDarkly SDK cache""" - self.ld_client.flush() + # LaunchDarkly is unavailable, the key is unknown, or targeting is off. + log_student( + f"CONFIG MANAGER: '{config_key}' not served by LaunchDarkly; " + "using .ai_config_defaults.json" + ) + served = ServedConfig( + key=config_key, + config=self._get_default_config(config_key), + from_fallback=True, + ) + log_debug(f"CONFIG MANAGER: Fallback model: {served.model_name}") + return served + + async def track( + self, + served: ServedConfig, + context: dict, + call, + user_input: str = None, + tool_handlers: dict = None, + capture_content: bool = False, + ): + """Run a model call through the AI SDK and record metrics + OTel spans in LaunchDarkly. + + `capture_content` is False by default so raw PII on supervisor/security calls + is never exported on spans; `support-agent` enables it because its input is already redacted. + """ + box = {} + takes_args = len(inspect.signature(call).parameters) > 0 + tracer = trace.get_tracer(TRACER_NAME) + + def _wrap_tools_with_spans(tools_map: dict) -> dict: + wrapped = {} + for name, fn in (tools_map or {}).items(): + async def traced_tool(_name=name, _fn=fn, **kwargs): + with tracer.start_as_current_span(f"execute_tool {_name}") as tool_span: + tool_span.set_attribute("gen_ai.operation.name", "execute_tool") + tool_span.set_attribute("gen_ai.tool.name", _name) + res = await _fn(**kwargs) + set_tool_call_content_attributes(tool_span, capture_content, arguments=kwargs, result=res) + return res + wrapped[name] = traced_tool + return wrapped + + async def handler(_cfg, _input, tracked_tools, variables, _history): + with tracer.start_as_current_span(f"invoke_agent {served.key}") as span: + span.set_attribute("gen_ai.operation.name", "invoke_agent") + set_model_identity_attributes(span, served.provider_name.lower(), served.model_name, legacy_system="langchain") + set_ld_span_attributes(span, variables, capture_content=capture_content) + if capture_content: + set_input_content_attributes( + span, + True, + system_instructions=served.render_instructions(variables), + messages=[text_message("user", _input or "")] if _input else None, + ) + try: + spanned_tools = _wrap_tools_with_spans(tracked_tools) + out = await (call(spanned_tools, variables) if takes_args else call()) + if len(out) == 3: + box["result"], output_text, raw_usage = out + else: + box["result"], raw_usage = out + output_text = str(box["result"]) if box["result"] is not None else "" + parsed = parse_usage(raw_usage or {}) + set_usage_span_attributes(span, SpanUsage(input=parsed["input"], output=parsed["output"])) + if capture_content and output_text: + set_output_content_attributes(span, True, [text_message("assistant", output_text)]) + span.set_status(SpanStatusCode.OK) + return {"output": output_text, "usage": raw_usage or {}} + except Exception as exc: + span.record_exception(exc) + span.set_status(SpanStatusCode.ERROR, str(exc)) + raise + + if served.from_fallback: + raw = await handler(served.config, user_input, tool_handlers or {}, {"ldContext": context}, None) + usage = parse_usage(raw["usage"]) + track_data = served.track_data() + else: + tracked = await execute_and_track( + config_key=served.key, + config=served.config, + meta=served.meta, + user_context=context, + handler=create_handler((served.provider_name, "agent"), handler), + user_input=user_input, + tool_handlers=tool_handlers, + ) + usage, track_data = tracked["usage"], tracked["track_data"] + + if usage["total"] > 0: + log_student(f"{served.key.upper()} TOKENS: {usage['total']} ({usage['input']} in, {usage['output']} out)") + cost = calculate_cost(served.model_name, usage["input"], usage["output"]) + if cost > 0: + try: + self._track("ai_cost_per_request", context, track_data, cost) + except Exception as e: + log_debug(f"COST TRACKING ERROR: {e}") + + return box["result"] + + def flush_traces(self): + """Export queued OpenTelemetry spans immediately so UI trace links resolve right away.""" + flush = getattr(trace.get_tracer_provider(), "force_flush", None) + if callable(flush): + try: + flush() + except Exception as e: + log_debug(f"TRACE FLUSH SKIPPED: {e}") def flush_metrics(self): - """Flush metrics to LaunchDarkly""" - self.ld_client.flush() - - def track_cost_metric(self, agent_config, context, cost, config_key): - """Track cost metric with AI Config metadata for experiment attribution. - - This ensures cost events include trackJsonData so they're properly - associated with AI Config variations in experiments, matching the - pattern used by token and feedback tracking. - - Args: - agent_config: The AI config object with tracker - context: LaunchDarkly context - cost: Cost value in dollars - config_key: The AI config key (e.g., 'support-agent', 'security-agent') - """ + """Flush pending LaunchDarkly events and OpenTelemetry spans if initialized.""" + self.flush_traces() try: - # Extract metadata from agent_config for experiment attribution - tracker = agent_config.create_tracker() - metadata = { - "version": 1, - "configKey": config_key, - "variationKey": tracker._variation_key if hasattr(tracker, '_variation_key') else 'unknown', - "modelName": agent_config.model.name if hasattr(agent_config, 'model') else 'unknown', - "providerName": agent_config.provider.name if hasattr(agent_config, 'provider') else 'unknown' - } - - # Track with metadata - this creates trackJsonData in the event - self.ld_client.track("ai_cost_per_request", context, metadata, cost) - self.ld_client.flush() - + get_client().flush() except Exception as e: - log_debug(f"COST TRACKING ERROR: {e}") - # Fallback to basic tracking if metadata extraction fails - self.ld_client.track("ai_cost_per_request", context, None, cost) - self.ld_client.flush() - - def track_feedback(self, tracker, thumbs_up: bool): - """Track user feedback with LaunchDarkly""" - if not tracker: + log_debug(f"FLUSH SKIPPED (client not initialized yet): {e}") + + @staticmethod + def _track(event: str, context: dict, data, value): + """Send a custom event. LDClient.track needs a Context, not a dict.""" + client = get_client() + client.track(event, to_ld_context(client, context), data, value) + client.flush() + + def track_feedback(self, served: Optional[ServedConfig], context, thumbs_up: bool) -> bool: + """Track user feedback with LaunchDarkly, attributed to the served variation.""" + if not served: return False try: - # Use LaunchDarkly's feedback tracking - feedback_dict = { - "kind": FeedbackKind.Positive if thumbs_up else FeedbackKind.Negative - } - tracker.track_feedback(feedback_dict) + event = FEEDBACK_POSITIVE_EVENT if thumbs_up else FEEDBACK_NEGATIVE_EVENT + self._track(event, context, served.track_data(), 1) log_student(f"FEEDBACK TRACKED: {'πŸ‘ Positive' if thumbs_up else 'πŸ‘Ž Negative'}") - self.ld_client.flush() return True except Exception as e: log_debug(f"FEEDBACK TRACKING ERROR: {e}") return False - def close(self): - """Close LaunchDarkly client""" - try: - self.ld_client.flush() - except Exception: - pass - try: - self.ld_client.close() - except Exception: - pass \ No newline at end of file + async def aclose(self): + """Flush pending LaunchDarkly events and telemetry spans, then close the client.""" + await shutdown() diff --git a/data/vector_store.py b/data/vector_store.py index 43ab805..85544b6 100644 --- a/data/vector_store.py +++ b/data/vector_store.py @@ -64,22 +64,10 @@ def __init__(self, store_path: str = "data/vector_store", provider: str = None): # Auto-detect provider if not specified self.provider = provider or self._detect_provider() - # Log provider selection with migration context - explicit_provider = os.getenv('EMBEDDING_PROVIDER', '').lower() - if explicit_provider: + if os.getenv('EMBEDDING_PROVIDER'): log_student(f"EMBEDDINGS: Using explicit provider: {self.provider}") - log_debug(f"MIGRATION: Provider explicitly set via EMBEDDING_PROVIDER={explicit_provider}") else: log_student(f"EMBEDDINGS: Auto-detected provider: {self.provider}") - auth_method = os.getenv('AUTH_METHOD', 'api-key').lower() - has_openai = os.getenv('OPENAI_API_KEY') - - if auth_method == 'sso' and not has_openai: - log_debug("MIGRATION: Auto-selected Bedrock (AUTH_METHOD=sso, no OpenAI key)") - elif has_openai: - log_debug("MIGRATION: Auto-selected OpenAI (API key available)") - else: - log_debug("MIGRATION: Defaulted to OpenAI (backward compatibility)") # Initialize provider-specific client and settings self._initialize_embedding_client() @@ -317,23 +305,9 @@ def _load_store(self): log_student( f"⚠️ PROVIDER MISMATCH: Vector store uses {stored_provider}, " f"but current config uses {self.provider}. " - f"Run 'initialize_embeddings.py --force' to rebuild for {self.provider}." + f"Run 'initialize_embeddings.py --force' to rebuild for {self.provider}, " + f"or set EMBEDDING_PROVIDER={stored_provider} to keep these embeddings." ) - - # Enhanced migration guidance - if stored_provider == "openai" and self.provider == "bedrock": - log_debug("MIGRATION: OpenAI β†’ Bedrock transition detected") - log_debug("MIGRATION: Consider hybrid setup: keep OpenAI embeddings, use Bedrock chat") - log_debug("MIGRATION: Set EMBEDDING_PROVIDER=openai to preserve embeddings") - elif stored_provider == "bedrock" and self.provider == "openai": - log_debug("MIGRATION: Bedrock β†’ OpenAI transition detected") - log_debug("MIGRATION: Embeddings will change from Titan to OpenAI model") - else: - log_debug(f"MIGRATION: {stored_provider} β†’ {self.provider} transition requires rebuild") - - self.index = None - self.documents = [] - self.metadata = [] return # Validate dimension compatibility @@ -343,21 +317,6 @@ def _load_store(self): f"but current config expects {self.dimension}. " f"Run 'initialize_embeddings.py --force' to rebuild." ) - - # Enhanced dimension migration guidance - if stored_dimension == 1536 and self.dimension == 1024: - log_debug("MIGRATION: OpenAI (1536) β†’ Bedrock (1024) dimension change") - log_debug("MIGRATION: Bedrock Titan V2 uses configurable dimensions") - log_debug("MIGRATION: Set BEDROCK_EMBEDDING_DIMENSIONS=1536 to match OpenAI") - elif stored_dimension == 1024 and self.dimension == 1536: - log_debug("MIGRATION: Bedrock (1024) β†’ OpenAI (1536) dimension change") - log_debug("MIGRATION: OpenAI text-embedding-3-small uses fixed 1536 dimensions") - else: - log_debug(f"MIGRATION: Dimension change {stored_dimension} β†’ {self.dimension}") - - self.index = None - self.documents = [] - self.metadata = [] return # If validation passes, load the store diff --git a/main.py b/main.py deleted file mode 100644 index cebb277..0000000 --- a/main.py +++ /dev/null @@ -1,6 +0,0 @@ -def main(): - print("Hello from agents-demo!") - - -if __name__ == "__main__": - main() diff --git a/pyproject.toml b/pyproject.toml index 3a02dc8..825d9e8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,7 +2,7 @@ name = "agents-demo" version = "0.1.0" description = "LaunchDarkly AI Configs tutorial with LangGraph agents" -requires-python = ">=3.11" +requires-python = ">=3.12" dependencies = [ # Agent Framework "langchain>=0.1.0", @@ -13,8 +13,8 @@ dependencies = [ "uvicorn[standard]>=0.24.0", "pydantic>=2.0.0", # LaunchDarkly - "launchdarkly-server-sdk>=9.0.0", - "launchdarkly-server-sdk-ai>=0.20.0", + "launchdarkly-server-sdk>=9.18.4", + "launchdarkly-ai-server[otel]>=1.1.0", # AWS Bedrock Integration "langchain-aws>=0.2.0", "boto3>=1.35.0", @@ -36,7 +36,6 @@ dependencies = [ "langchain-mcp-adapters>=0.1.9", "beautifulsoup4>=4.13.5", "mcp>=1.13.1", - "semanticscholar>=0.10.0", "rank-bm25>=0.2.2", "langchain-mistralai>=0.2.12", ] @@ -53,3 +52,8 @@ dev = [ [tool.setuptools] packages = ["api", "agents"] + +[tool.pytest.ini_options] +# api/segmentation_test.py is a live script that needs the running API, not a unit test +testpaths = ["tests"] +asyncio_mode = "auto" diff --git a/screenshots/chat_interface.png b/screenshots/chat_interface.png index 31d494e..5abd8f9 100644 Binary files a/screenshots/chat_interface.png and b/screenshots/chat_interface.png differ diff --git a/screenshots/ui_small.png b/screenshots/ui_small.png index 1d6c36b..511e3b3 100644 Binary files a/screenshots/ui_small.png and b/screenshots/ui_small.png differ diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..2149ae6 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,32 @@ +"""Shared setup for the unit tests: no network, no real keys, run from the repo root.""" +import os +import sys +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO_ROOT)) + +# Set before the app modules import and load .env, which never overrides existing values +os.environ["LD_SDK_KEY"] = "sdk-test-key" +os.environ["LD_API_KEY"] = "api-test-key" +os.environ["AUTH_METHOD"] = "api-key" +os.environ["CI_SAFE_MODE"] = "" + + +@pytest.fixture(autouse=True) +def run_from_repo_root(monkeypatch): + """The config manager reads .ai_config_defaults.json from the working directory.""" + monkeypatch.chdir(REPO_ROOT) + + +@pytest.fixture(autouse=True) +def no_rate_limit_sleep(monkeypatch): + """The agents pause between model calls; the fakes don't need that.""" + import agents.ld_agent_helpers as helpers + import agents.security_agent as security + import agents.supervisor_agent as supervisor + + for module in (helpers, security, supervisor): + monkeypatch.setattr(module, "_rate_limit_llm_call", lambda: None) diff --git a/tests/fakes.py b/tests/fakes.py new file mode 100644 index 0000000..97989c0 --- /dev/null +++ b/tests/fakes.py @@ -0,0 +1,84 @@ +"""Small stand-ins for the model, the agents, and the config manager, so tests never call an API.""" +import inspect +from langchain_core.messages import AIMessage + +from config_manager import ServedConfig + + +def served(key, model="claude-haiku-5-5", custom=None, tools=None, variation_key=None): + """A config as LaunchDarkly would serve it, or a local fallback when variation_key is None.""" + tool_list = tools or [] + config = { + "model": {"name": model, "custom": custom or {}, "parameters": {"tools": tool_list}}, + "provider": {"name": "Anthropic"}, + "instructions": f"You are the {key}.", + "tools": { + t["name"]: {**t, "type": "function"} + for t in tool_list + if isinstance(t, dict) and "name" in t + }, + } + if variation_key is None: + return ServedConfig(key=key, config=config, from_fallback=True) + return ServedConfig( + key=key, + config=config, + meta={"variationKey": variation_key, "version": 1, "modelKey": f"Anthropic.{model}", "modelVersion": 1}, + ) + + +class FakeConfigManager: + """Serves fixed configs and runs model calls without sending events.""" + + def __init__(self, configs): + self.configs = configs + + async def get_config(self, user_id, config_key, user_context=None): + return self.configs[config_key] + + def build_context(self, user_id, user_context=None): + return {"kind": "user", "key": user_id, **(user_context or {})} + + async def track(self, served_config, context, call, user_input=None, tool_handlers=None, capture_content=False): + takes_args = len(inspect.signature(call).parameters) > 0 + out = await (call(tool_handlers or {}, {"ldContext": context}) if takes_args else call()) + return out[0] + + +class FakeStructuredModel: + """Returns one structured result, like with_structured_output(..., include_raw=True).""" + + def __init__(self, parsed=None, error=None): + self.parsed = parsed + self.error = error + + def with_structured_output(self, schema, include_raw=False): + return self + + async def ainvoke(self, messages): + if self.error: + raise self.error + usage = {"input_tokens": 10, "output_tokens": 5, "total_tokens": 15} + return {"parsed": self.parsed, "raw": AIMessage(content="", usage_metadata=usage)} + + +class RecordingSupportAgent: + """Records exactly what the support agent receives.""" + + def __init__(self): + self.received = None + + async def ainvoke(self, request_data): + self.received = request_data + return {"response": "Here is what I found.", "tool_calls": [], "tool_details": []} + + +class FixedSecurityAgent: + """Returns a fixed PII result instead of calling a model.""" + + def __init__(self, redacted, detected=True): + self.result = {"detected": detected, "types": ["email"] if detected else [], "redacted": redacted, + "response": "PII Analysis: done"} + + async def ainvoke(self, request_data): + return self.result diff --git a/tests/test_bedrock_model_ids.py b/tests/test_bedrock_model_ids.py new file mode 100644 index 0000000..b909214 --- /dev/null +++ b/tests/test_bedrock_model_ids.py @@ -0,0 +1,30 @@ +"""With AUTH_METHOD=sso, model names from LaunchDarkly become Bedrock inference profile IDs.""" +import pytest + +from utils.bedrock_helpers import ensure_bedrock_inference_profile +from utils.cost_calculator import calculate_cost + + +@pytest.fixture(autouse=True) +def no_region_override(monkeypatch): + monkeypatch.delenv("BEDROCK_INFERENCE_REGION", raising=False) + + +@pytest.mark.parametrize("model_id, expected", [ + ("claude-haiku-5-5", "us.anthropic.claude-haiku-5-5"), + ("anthropic.claude-sonnet-5-5", "us.anthropic.claude-sonnet-5-5"), + ("us.anthropic.claude-opus-5-5", "us.anthropic.claude-opus-5-5"), + ("global.anthropic.claude-haiku-5-5", "global.anthropic.claude-haiku-5-5"), + ("us-gov.anthropic.claude-haiku-5-5", "us-gov.anthropic.claude-haiku-5-5"), +]) +def test_model_ids_become_inference_profiles(model_id, expected): + assert ensure_bedrock_inference_profile(model_id, "us-east-1") == expected + + +def test_inference_region_override(monkeypatch): + monkeypatch.setenv("BEDROCK_INFERENCE_REGION", "eu") + assert ensure_bedrock_inference_profile("claude-haiku-5-5", "us-east-1") == "eu.anthropic.claude-haiku-5-5" + + +def test_bedrock_ids_are_priced_by_claude_tier(): + assert calculate_cost("us.anthropic.claude-haiku-5-5", 1_000_000, 0) == calculate_cost("claude-haiku-5-5", 1_000_000, 0) diff --git a/tests/test_bootstrap_payloads.py b/tests/test_bootstrap_payloads.py new file mode 100644 index 0000000..a71cb92 --- /dev/null +++ b/tests/test_bootstrap_payloads.py @@ -0,0 +1,144 @@ +"""The bootstrap scripts send custom parameters where LaunchDarkly stores them: model.custom.""" +from pathlib import Path + +import yaml + +import bootstrap.create_configs as create_configs +import bootstrap.tutorial_3_experiment_variations as tutorial_3 + + +class FakeResponse: + status_code = 201 + text = "" + + def json(self): + return {} + + +def manifest_variation(config_key, variation_key): + manifest = yaml.safe_load(Path("bootstrap/ai_config_manifest.yaml").read_text()) + config = next(c for c in manifest["project"]["ai_config"] if c["key"] == config_key) + return next(v for v in config["variations"] if v["key"] == variation_key) + + +def test_part_2_variations_send_max_tool_calls(monkeypatch): + sent = [] + monkeypatch.setattr(create_configs.http, "post", lambda url, headers, json, timeout: sent.append(json) or FakeResponse()) + monkeypatch.setattr(create_configs.time, "sleep", lambda seconds: None) + + bootstrap = create_configs.MultiAgentBootstrap("api-test-key") + bootstrap.create_variation("multi-agent-chatbot", "support-agent", manifest_variation("support-agent", "eu-paid")) + + payload = sent[0] + assert payload["modelConfigKey"] == "Anthropic.claude-sonnet-5-5" + assert payload["model"]["custom"]["max_tool_calls"] == 20 + + +def test_part_3_variation_sends_max_tool_calls(monkeypatch): + sent = [] + monkeypatch.setattr(tutorial_3.requests, "post", lambda url, json, headers, timeout: sent.append(json) or FakeResponse()) + monkeypatch.setattr(tutorial_3.time, "sleep", lambda seconds: None) + + assert tutorial_3.Tutorial3VariationBootstrap().create_premium_model_variations() + + payload = sent[0] + assert payload["modelConfigKey"] == "Anthropic.claude-opus-5-5" + assert payload["model"] == {"custom": {"max_tool_calls": 10}} + assert "max_tool_calls" not in payload + + +def test_unmapped_provider_fallback_uses_canonical_provider_casing(monkeypatch): + sent = [] + monkeypatch.setattr(create_configs.http, "post", lambda url, headers, json, timeout: sent.append(json) or FakeResponse()) + monkeypatch.setattr(create_configs.time, "sleep", lambda seconds: None) + + bootstrap = create_configs.MultiAgentBootstrap("api-test-key") + bootstrap.create_variation( + "multi-agent-chatbot", + "support-agent", + { + "key": "custom-openai", + "instructions": "Help the user.", + "modelConfig": {"provider": "openai", "modelId": "gpt-custom-preview"}, + "tools": [], + }, + ) + + payload = sent[0] + assert payload["modelName"] == "gpt-custom-preview" + assert payload["provider"] == {"name": "OpenAI"} + + +def test_part_3_free_mistral_option_and_provider_casing(monkeypatch): + sent = [] + monkeypatch.setattr(tutorial_3.requests, "post", lambda url, json, headers, timeout: sent.append(json) or FakeResponse()) + monkeypatch.setattr(tutorial_3.time, "sleep", lambda seconds: None) + + boot = tutorial_3.Tutorial3VariationBootstrap() + assert boot._create_variations( + "support-agent", + [ + { + "key": "mistral-free", + "name": "Mistral Free", + "instructions": "Help the user.", + "model": {"name": "mistral-small-latest", "provider": "mistral"}, + "tools": ["search_v1"], + "customParameters": {"max_tool_calls": 10}, + }, + { + "key": "mistral-custom", + "name": "Mistral Custom", + "instructions": "Help the user.", + "model": {"name": "mistral-custom-preview", "provider": "mistral"}, + "tools": ["search_v1"], + "customParameters": {"max_tool_calls": 10}, + }, + ], + ) + + assert sent[0]["modelConfigKey"] == "Mistral.mistral-small-latest" + assert sent[1]["modelName"] == "mistral-custom-preview" + assert sent[1]["provider"] == {"name": "Mistral"} + + +def test_dynamic_tools_accept_integer_top_k_and_string_rerank_results(monkeypatch): + from tools_impl.dynamic_tool_factory import _create_dynamic_reranking_tool, _create_dynamic_search_v2 + import tools_impl.search_v2 as search_v2_mod + + seen = {} + + def fake_run(self, query, top_k=3, **kwargs): + seen["top_k"] = top_k + return f"hit:{query}:{top_k}" + + monkeypatch.setattr(search_v2_mod.SearchToolV2, "_run", fake_run) + + search_tool = _create_dynamic_search_v2( + { + "type": "object", + "properties": { + "query": {"type": "string"}, + "top_k": {"type": "integer"}, + }, + "required": ["query"], + } + ) + assert search_tool.invoke({"query": "reinforcement learning", "top_k": None}) == "hit:reinforcement learning:3" + assert seen["top_k"] == 3 + + rerank_tool = _create_dynamic_reranking_tool( + { + "type": "object", + "properties": { + "query": {"type": "string"}, + "results": {"type": "array"}, + }, + "required": ["query"], + } + ) + out = rerank_tool.invoke({"query": "policy gradient", "results": ["doc about policy gradient", "other doc"]}) + assert "BM25 reranked results" in out + assert "No search results found" in rerank_tool.invoke({"query": "policy gradient"}) + + diff --git a/tests/test_config_and_tracking.py b/tests/test_config_and_tracking.py new file mode 100644 index 0000000..7af77ab --- /dev/null +++ b/tests/test_config_and_tracking.py @@ -0,0 +1,157 @@ +"""Local defaults when LaunchDarkly is unavailable, and events attributed to the served variation.""" +import config_manager +from config_manager import FEEDBACK_POSITIVE_EVENT, FixedConfigManager +from launchdarkly_ai_server import init_client, parse_usage, shutdown +from tests.fakes import served + + +async def test_unreachable_launchdarkly_serves_defaults_and_backs_off(monkeypatch): + attempts = [] + + async def unreachable(options=None): + attempts.append(options) + raise RuntimeError("LaunchDarkly client failed to initialize") + + monkeypatch.setattr(config_manager, "init_client", unreachable) + manager = FixedConfigManager() + + for key in ["supervisor-agent", "support-agent", "security-agent"]: + config = await manager.get_config("u1", key, {"plan": "free"}) + assert config.from_fallback + assert config.model_name == "claude-haiku-5-5" + assert config.variation_key == "fallback" + + # Only the first call waits for LaunchDarkly; the rest serve defaults right away + assert len(attempts) == 1 + + +async def test_disabled_config_serves_defaults(monkeypatch): + async def connected(options=None): + return None + + async def disabled(config_key, context): + return {"enabled": False, "config": None, "meta": {"enabled": False}} + + monkeypatch.setattr(config_manager, "init_client", connected) + monkeypatch.setattr(config_manager, "inspect_config", disabled) + + config = await FixedConfigManager().get_config("u1", "support-agent") + assert config.from_fallback + assert [tool["name"] for tool in config.parameters["tools"]] == ["search_v1", "search_v2", "reranking"] + + +def capture_events(monkeypatch): + events = [] + monkeypatch.setattr(FixedConfigManager, "_track", + staticmethod(lambda event, context, data, value: events.append((event, data, value)))) + return events + + +def test_feedback_is_attributed_to_the_served_variation(monkeypatch): + events = capture_events(monkeypatch) + support_config = served("support-agent", variation_key="other-paid") + + assert FixedConfigManager().track_feedback(support_config, {"kind": "user", "key": "u1"}, thumbs_up=True) + + event, data, value = events[0] + assert event == FEEDBACK_POSITIVE_EVENT + assert data["variationKey"] == "other-paid" + assert data["configKey"] == "support-agent" + + +async def test_cost_event_uses_the_served_variation(monkeypatch): + events = capture_events(monkeypatch) + support_config = served("support-agent", variation_key="other-paid") + + async def fake_execute_and_track(**kwargs): + handler_result = await kwargs["handler"](kwargs["config"], kwargs.get("user_input"), {}, {"ldContext": kwargs["user_context"]}, None) + assert handler_result["output"] == "answer" + return {"usage": parse_usage(handler_result["usage"]), + "track_data": {"configKey": "support-agent", "variationKey": "other-paid"}} + + monkeypatch.setattr(config_manager, "create_handler", lambda provides_for, fn: fn) + monkeypatch.setattr(config_manager, "execute_and_track", fake_execute_and_track) + + async def model_call(): + return "answer", {"input_tokens": 1000, "output_tokens": 500} + + result = await FixedConfigManager().track(support_config, {"kind": "user", "key": "u1"}, model_call) + + assert result == "answer" + event, data, value = events[0] + assert event == "ai_cost_per_request" + assert data["variationKey"] == "other-paid" + assert value > 0 + + +async def test_sdk_tool_handlers_emit_tool_call_events_and_render_templates(monkeypatch): + import agents.ld_agent_helpers as helpers + + class FakeLDClient: + def __init__(self): + self.tracked = [] + + def track(self, event, context, data, value=1): + self.tracked.append((event, data, value)) + + def flush(self): + pass + + await shutdown() + fake_ld = FakeLDClient() + await init_client(client=fake_ld) + try: + tool_spec = {"name": "search_v2", "description": "Search", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}}} + support_config = served("support-agent", variation_key="other-paid", tools=[tool_spec]) + support_config.config["instructions"] = "Helping a {{ldContext.plan}} customer." + + async def search_impl(**kwargs): + return f"hit:{kwargs['query']}" + + seen_prompt = {} + + async def run_turn(tracked_tools, variables): + seen_prompt["text"] = support_config.render_instructions(variables) + res = await tracked_tools["search_v2"](query="q-learning") + return res, f"Final: {res}", {"input_tokens": 20, "output_tokens": 10} + + ctx = {"kind": "user", "key": "u1", "plan": "paid"} + result = await FixedConfigManager().track( + support_config, ctx, run_turn, user_input="What is Q-learning?", tool_handlers={"search_v2": search_impl} + ) + + assert result == "hit:q-learning" + assert seen_prompt["text"] == "Helping a paid customer." + event_names = [e for e, _, _ in fake_ld.tracked] + assert "$ld:ai:tool_call" in event_names + assert "$ld:ai:generation:success" in event_names + tool_event = next(data for e, data, _ in fake_ld.tracked if e == "$ld:ai:tool_call") + assert tool_event["toolKey"] == "search_v2" + assert tool_event["modelKey"] == "Anthropic.claude-haiku-5-5" + assert "runId" in tool_event + + # Verify create_chat_model forwards model.parameters while stripping attached tools + forwarded = {} + monkeypatch.setattr(helpers, "init_chat_model", lambda **kw: forwarded.update(kw) or "llm") + helpers.create_chat_model("Anthropic", "claude-haiku-5-5", None, {"max_tokens": 512, "tools": [tool_spec]}) + assert forwarded == {"model": "claude-haiku-5-5", "model_provider": "anthropic", "max_tokens": 512} + finally: + await shutdown() + + +def test_flush_traces_uses_public_otel_provider(monkeypatch): + flushed = [] + + class FakeTracerProvider: + def force_flush(self): + flushed.append(True) + + monkeypatch.setattr(config_manager.trace, "get_tracer_provider", lambda: FakeTracerProvider()) + manager = FixedConfigManager() + manager.flush_traces() + assert flushed == [True] + + # Proxy/no-op provider without force_flush must be a safe no-op + monkeypatch.setattr(config_manager.trace, "get_tracer_provider", lambda: object()) + manager.flush_traces() + diff --git a/tests/test_openalex_tokens.py b/tests/test_openalex_tokens.py new file mode 100644 index 0000000..fcb230d --- /dev/null +++ b/tests/test_openalex_tokens.py @@ -0,0 +1,94 @@ +"""OpenAlex tokens refresh from the token file, without a real sign-in or network.""" +import json +import stat +import time + +import tools_impl.mcp_research_tools as mcp_tools +import tools_impl.openalex_auth as openalex_auth + +STORED = { + "client_info": {"client_id": "test-client", "redirect_uris": ["http://localhost:3030/callback"]}, + "tokens": {"access_token": "old-access", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "old-refresh"}, +} + + +class FakeResponse: + def __init__(self, body): + self.body = body + + def raise_for_status(self): + pass + + def json(self): + return self.body + + +class FakeHttpClient: + """Stands in for httpx.AsyncClient and records the refresh request.""" + requests = [] + response = {"access_token": "new-access", "token_type": "Bearer", "expires_in": 3600} + + async def __aenter__(self): + return self + + async def __aexit__(self, *args): + pass + + async def post(self, url, data): + FakeHttpClient.requests.append(data) + return FakeResponse(FakeHttpClient.response) + + +def token_file(tmp_path, monkeypatch, expires_at): + path = tmp_path / "openalex_tokens.json" + path.write_text(json.dumps({**STORED, "expires_at": expires_at})) + monkeypatch.setattr(openalex_auth, "TOKEN_FILE", path) + monkeypatch.setattr(openalex_auth.httpx, "AsyncClient", FakeHttpClient) + FakeHttpClient.requests = [] + return path + + +async def test_expired_tokens_are_refreshed_and_keep_the_refresh_token(tmp_path, monkeypatch): + path = token_file(tmp_path, monkeypatch, expires_at=time.time() - 10) + + tokens = await openalex_auth.FileTokenStorage().get_tokens() + + assert tokens.access_token == "new-access" + assert tokens.refresh_token == "old-refresh" + assert FakeHttpClient.requests[0]["refresh_token"] == "old-refresh" + saved = json.loads(path.read_text()) + assert saved["tokens"]["refresh_token"] == "old-refresh" + assert saved["expires_at"] > time.time() + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + + +async def test_valid_tokens_are_used_without_a_refresh(tmp_path, monkeypatch): + token_file(tmp_path, monkeypatch, expires_at=time.time() + 600) + + tokens = await openalex_auth.FileTokenStorage().get_tokens() + + assert tokens.access_token == "old-access" + assert FakeHttpClient.requests == [] + + +async def test_each_search_gets_a_fresh_oauth_provider(): + class FakeSearchWorks: + name = "search_works" + + def __init__(self, connection): + self.connection = connection + self.auth_per_call = [] + + async def ainvoke(self, args): + self.auth_per_call.append(self.connection["auth"]) + return f"works about {args['query']}" + + connection = {"transport": "streamable_http", "url": openalex_auth.OPENALEX_MCP_URL, "auth": None} + search_works = FakeSearchWorks(connection) + tool = mcp_tools._query_only(search_works, connection) + + assert await tool.ainvoke({"query": "reinforcement learning"}) == "works about reinforcement learning" + await tool.ainvoke({"query": "q-learning"}) + + first, second = search_works.auth_per_call + assert first is not second diff --git a/tests/test_security_boundary.py b/tests/test_security_boundary.py new file mode 100644 index 0000000..bdbbf0b --- /dev/null +++ b/tests/test_security_boundary.py @@ -0,0 +1,86 @@ +"""PII never reaches the support agent, and conversation history survives a PII turn.""" +import agents.security_agent as security +import agents.supervisor_agent as supervisor +from agents.security_agent import WITHHELD_MESSAGE, PIIDetectionResponse +from agents.supervisor_agent import PIIPreScreening +from api.services.agent_service import AgentService +from tests.fakes import FakeConfigManager, FakeStructuredModel, FixedSecurityAgent, RecordingSupportAgent, served + +RAW_MESSAGE = "My email is jane.roe@example.com. What did I ask before?" +REDACTED_MESSAGE = "My email is [REDACTED]. What did I ask before?" +HISTORY = [ + {"role": "user", "content": "What is Q-learning?"}, + {"role": "assistant", "content": "Q-learning is an off-policy TD method."}, +] + + +def route_to_security(): + return FakeStructuredModel(PIIPreScreening(likely_contains_pii=True, confidence=1.0, + reasoning="contains an email", recommended_route="security_agent")) + + +async def run_chat(monkeypatch, security_agent, history=None): + """Run one /chat request through the real supervisor graph with fake agents.""" + support_agent = RecordingSupportAgent() + monkeypatch.setattr(supervisor, "create_chat_model", lambda *args: route_to_security()) + monkeypatch.setattr(supervisor, "create_security_agent", lambda *args: security_agent) + monkeypatch.setattr(supervisor, "create_support_agent", lambda *args: support_agent) + + service = AgentService() + service.config_manager = FakeConfigManager({ + "supervisor-agent": served("supervisor-agent"), + "security-agent": served("security-agent"), + "support-agent": served("support-agent"), + }) + response = await service.process_message("u1", RAW_MESSAGE, {"plan": "free"}, history) + return response, support_agent.received + + +def support_saw(received): + return [received["user_input"]] + [m.content for m in received["messages"]] + + +async def test_support_agent_gets_redacted_text(monkeypatch): + _, received = await run_chat(monkeypatch, FixedSecurityAgent(REDACTED_MESSAGE)) + + assert received["user_input"] == REDACTED_MESSAGE + assert not any("jane.roe@example.com" in text for text in support_saw(received)) + + +async def test_empty_redaction_withholds_the_message(monkeypatch): + _, received = await run_chat(monkeypatch, FixedSecurityAgent("")) + + assert received["user_input"] == WITHHELD_MESSAGE + assert not any("jane.roe@example.com" in text for text in support_saw(received)) + + +async def test_history_survives_a_pii_turn(monkeypatch): + _, received = await run_chat(monkeypatch, FixedSecurityAgent(REDACTED_MESSAGE), history=HISTORY) + + assert [m.content for m in received["messages"]] == [ + "What is Q-learning?", + "Q-learning is an off-policy TD method.", + REDACTED_MESSAGE, + ] + + +async def run_security_agent(monkeypatch, model): + monkeypatch.setattr(security, "create_chat_model", lambda *args: model) + agent = security.create_security_agent(None, FakeConfigManager({"security-agent": served("security-agent")})) + return await agent.ainvoke({"user_input": RAW_MESSAGE, "user_id": "u1", "messages": [("user", RAW_MESSAGE)]}) + + +async def test_security_agent_fails_closed_on_error(monkeypatch): + result = await run_security_agent(monkeypatch, FakeStructuredModel(error=RuntimeError("429 Too Many Requests"))) + assert result["redacted"] == WITHHELD_MESSAGE + + +async def test_security_agent_fails_closed_without_structured_output(monkeypatch): + result = await run_security_agent(monkeypatch, FakeStructuredModel(parsed=None)) + assert result["redacted"] == WITHHELD_MESSAGE + + +async def test_security_agent_returns_the_redaction(monkeypatch): + parsed = PIIDetectionResponse(detected=True, types=["email"], redacted=REDACTED_MESSAGE) + result = await run_security_agent(monkeypatch, FakeStructuredModel(parsed=parsed)) + assert result["redacted"] == REDACTED_MESSAGE diff --git a/tests/test_tool_limit.py b/tests/test_tool_limit.py new file mode 100644 index 0000000..5bed19d --- /dev/null +++ b/tests/test_tool_limit.py @@ -0,0 +1,52 @@ +"""max_tool_calls from LaunchDarkly stops the support agent at the limit.""" +from langchain_core.language_models.fake_chat_models import GenericFakeChatModel +from langchain_core.messages import AIMessage +from langchain_core.tools import BaseTool +from pydantic import BaseModel + +import agents.ld_agent_helpers as helpers +from tests.fakes import FakeConfigManager, served + + +class SearchInput(BaseModel): + query: str + + +class CountingSearch(BaseTool): + name: str = "search_v2" + description: str = "Semantic search using vector embeddings" + args_schema: type[BaseModel] = SearchInput + calls: int = 0 + + def _run(self, query: str) -> str: + self.calls += 1 + return f"Result for {query}" + + +class ToolHappyModel(GenericFakeChatModel): + """A model that asks for one more search every turn.""" + + def bind_tools(self, tools, **kwargs): + return self + + +def search_request(n): + return AIMessage(content="", tool_calls=[{"name": "search_v2", "args": {"query": f"q{n}"}, "id": f"call_{n}"}]) + + +async def test_agent_stops_at_max_tool_calls(monkeypatch): + model = ToolHappyModel(messages=iter([search_request(n) for n in range(10)])) + monkeypatch.setattr(helpers, "create_chat_model", lambda *args: model) + + search = CountingSearch() + config_manager = FakeConfigManager({"support-agent": served("support-agent", custom={"max_tool_calls": 2})}) + agent = helpers.create_simple_agent_wrapper(config_manager, "support-agent", [search]) + + result = await agent.ainvoke({"user_input": "Research everything", "user_id": "u1"}) + + assert search.calls == 2 + assert result["response"].startswith("I've reached the tool call limit for this request.") + + +def test_other_tool_errors_go_back_to_the_model(): + assert "boom" in helpers._tool_error_message(ValueError("boom")) diff --git a/tools.py b/tools.py index 77441e1..8fd6dde 100644 --- a/tools.py +++ b/tools.py @@ -16,6 +16,10 @@ from typing import List, Dict, Any, Optional +def _ci_safe_mode() -> bool: + return os.getenv("CI_SAFE_MODE", "").lower() in {"1", "true", "yes"} + + def search_v1(query: str) -> str: """ Basic keyword-based search through enterprise documentation. @@ -31,12 +35,8 @@ def search_v1(query: str) -> str: """ try: from tools_impl.search_v1 import SearchToolV1 - tool = SearchToolV1() - return tool._run(query) + return SearchToolV1()._run(query) except Exception as e: - import traceback - error_details = traceback.format_exc() - print(f"ERROR in search_v1: {type(e).__name__}: {str(e)}\n{error_details}") return f"Search error: {type(e).__name__}: {str(e)}. If this persists, ensure vector embeddings are initialized with 'uv run initialize_embeddings.py'" @@ -56,14 +56,8 @@ def search_v2(query: str, top_k: int = 3) -> str: """ try: from tools_impl.search_v2 import SearchToolV2 - tool = SearchToolV2() - # Clamp top_k for safety - top_k = max(1, min(int(top_k), 20)) - return tool._run(query, top_k) + return SearchToolV2()._run(query, top_k) except Exception as e: - import traceback - error_details = traceback.format_exc() - print(f"ERROR in search_v2: {type(e).__name__}: {str(e)}\n{error_details}") return f"Search error: {type(e).__name__}: {str(e)}. If this persists, ensure vector embeddings are initialized with 'uv run initialize_embeddings.py'" @@ -83,8 +77,7 @@ def reranking(query: str, results: Optional[List[Dict[str, Any]]] = None) -> str """ try: from tools_impl.reranking import RerankingTool - tool = RerankingTool() - return tool._run(query, results) + return RerankingTool()._run(query, results) except Exception as e: return f"Reranking error: {str(e)}" @@ -103,13 +96,12 @@ def arxiv_search(query: str, max_results: int = 5) -> str: Returns: Formatted string with ArXiv paper results including titles, authors, and abstracts """ - # Check if CI_SAFE_MODE is enabled (network-dependent tools disabled) - if os.getenv("CI_SAFE_MODE", "").lower() in {"1", "true", "yes"}: + if _ci_safe_mode(): return "ArXiv search is disabled in CI safe mode (network-dependent MCP tool)" try: from tools_impl.dynamic_tool_factory import _create_dynamic_mcp_tool - tool = _create_dynamic_mcp_tool("arxiv_search", {}) + tool = _create_dynamic_mcp_tool("arxiv_search") if tool is None: return "ArXiv MCP tool not available. Install with: uv tool install arxiv-mcp-server" return tool._run(query=query, max_results=max_results) @@ -117,35 +109,30 @@ def arxiv_search(query: str, max_results: int = 5) -> str: return f"ArXiv search error: {str(e)}" -def semantic_scholar(query: str, num_results: int = 3) -> str: +def openalex_search(query: str) -> str: """ - Access Semantic Scholar citation database for academic research. + Search OpenAlex for scholarly works and citation counts. - MCP tool that searches the Semantic Scholar database for papers and citations. - Requires semanticscholar-MCP-Server to be installed. Disabled in CI safe mode. - Always request fewer than 5 results to avoid rate limiting. + MCP tool that searches the OpenAlex catalog of papers, books, and datasets. + Requires a one-time sign-in with tools_impl/openalex_auth.py. Disabled in CI safe mode. Args: query: Academic research query - num_results: Number of papers to return (default: 3, recommended: <5) Returns: - Formatted string with Semantic Scholar paper results including citations + Formatted string with OpenAlex results including citation counts """ - # Check if CI_SAFE_MODE is enabled (network-dependent tools disabled) - if os.getenv("CI_SAFE_MODE", "").lower() in {"1", "true", "yes"}: - return "Semantic Scholar search is disabled in CI safe mode (network-dependent MCP tool)" + if _ci_safe_mode(): + return "OpenAlex search is disabled in CI safe mode (network-dependent MCP tool)" try: from tools_impl.dynamic_tool_factory import _create_dynamic_mcp_tool - # Clamp num_results to recommended max - num_results = max(1, min(int(num_results), 5)) - tool = _create_dynamic_mcp_tool("semantic_scholar", {}) + tool = _create_dynamic_mcp_tool("openalex_search") if tool is None: - return "Semantic Scholar MCP tool not available. Install from: https://github.com/JackKuo666/semanticscholar-MCP-Server" - return tool._run(query=query, num_results=num_results) + return "OpenAlex MCP tool not available. Sign in with: uv run python tools_impl/openalex_auth.py" + return tool._run(query=query) except Exception as e: - return f"Semantic Scholar search error: {str(e)}" + return f"OpenAlex search error: {str(e)}" # Tool metadata for LaunchDarkly AI Config registration @@ -155,5 +142,5 @@ def semantic_scholar(query: str, num_results: int = 3) -> str: "search_v2", "reranking", "arxiv_search", - "semantic_scholar" + "openalex_search" ] diff --git a/tools/concurrent_traffic_generator.py b/tools/concurrent_traffic_generator.py index f59b742..74a02cd 100755 --- a/tools/concurrent_traffic_generator.py +++ b/tools/concurrent_traffic_generator.py @@ -54,6 +54,7 @@ def get_user_id(self): def evaluate_response(self, query, response): """Ask Claude to evaluate if user would give feedback""" + # Every Claude call here disables thinking: Haiku 5.5 thinks by default, which uses up these small max_tokens budgets prompt = f"""Based on this Q&A, would a user give feedback? Question: {query[:200]} @@ -64,12 +65,13 @@ def evaluate_response(self, query, response): - negative (poor answer, user would thumbs down) - none (okay answer, user wouldn't bother rating) -Most users don't give feedback unless the answer is notably good or bad.""" +Users give a thumbs up to answers that fully and correctly answer the question, a thumbs down to answers that are wrong, evasive, or ask for information the question already gave, and no rating to answers that only partly help.""" try: ai_response = self.claude.messages.create( - model="claude-haiku-4-5-20251001", + model="claude-haiku-5-5", max_tokens=10, + thinking={"type": "disabled"}, messages=[{"role": "user", "content": prompt}] ) @@ -81,15 +83,16 @@ def evaluate_response(self, query, response): else: return "none" - except: + except Exception: return "none" # Default to no feedback on error def generate_base_topics(self): """Generate base RL topics""" try: response = self.claude.messages.create( - model="claude-haiku-4-5-20251001", + model="claude-haiku-5-5", max_tokens=800, + thinking={"type": "disabled"}, messages=[{ "role": "user", "content": """List 20 reinforcement learning topics from the Sutton & Barto textbook. @@ -145,19 +148,20 @@ def generate_query(self, topic, inject_pii=False): try: response = self.claude.messages.create( - model="claude-haiku-4-5-20251001", + model="claude-haiku-5-5", max_tokens=100, + thinking={"type": "disabled"}, messages=[{"role": "user", "content": prompt}] ) return response.content[0].text.strip() - except: + except Exception: # Fallback if inject_pii: return f"Hi, I'm John Smith (john.smith@email.com) and I need help with {topic}" else: return f"Can you explain {topic}?" - def send_single_request(self, query_num, query): + def send_single_request(self, total, query): """Send a single request and process response""" try: # Generate unique user @@ -204,20 +208,20 @@ def send_single_request(self, query_num, query): }, timeout=10 ) - except: + except Exception: pass # Feedback is optional with self.lock: self.successful += 1 self.completed += 1 - print(f"βœ… [{self.completed}/{query_num}] Success ({duration:.1f}s) - other_paid: {query[:60]}...") + print(f"βœ… [{self.completed}/{total}] Success ({duration:.1f}s) - other_paid: {query[:60]}...") return {"success": True, "duration": duration} else: with self.lock: self.failed += 1 self.completed += 1 - print(f"❌ [{self.completed}/{query_num}] Failed - {response.status_code}") + print(f"❌ [{self.completed}/{total}] Failed - {response.status_code}") return {"success": False, "error": response.status_code} @@ -225,25 +229,25 @@ def send_single_request(self, query_num, query): with self.lock: self.failed += 1 self.completed += 1 - print(f"⏱️ [{self.completed}/{query_num}] Timeout (>2000s) - {query[:60]}...") + print(f"⏱️ [{self.completed}/{total}] Timeout (>2000s) - {query[:60]}...") return {"success": False, "error": "timeout"} except Exception as e: with self.lock: self.failed += 1 self.completed += 1 - print(f"❌ [{self.completed}/{query_num}] Error: {e}") + print(f"❌ [{self.completed}/{total}] Error: {e}") return {"success": False, "error": str(e)} def run(self, num_queries): """Run traffic generation with concurrent requests""" - print(f"\nπŸš€ Concurrent Traffic Generator") - print(f"=" * 70) + print("\nπŸš€ Concurrent Traffic Generator") + print("=" * 70) print(f"Queries: {num_queries}") print(f"Concurrency: {self.concurrency} parallel requests") - print(f"Timeout: 2000s (33 minutes) per request") + print("Timeout: 2000s (33 minutes) per request") print(f"Target: {self.api_base_url}") - print(f"=" * 70) + print("=" * 70) # Generate base topics print("\nπŸ“š Generating base topics...") @@ -272,22 +276,11 @@ def run(self, num_queries): for task in query_tasks } - # Collect results as they complete + # Collect results as they complete (generate_query falls back to a template on errors) completed_count = 0 for future in as_completed(future_to_task): - task = future_to_task[future] - query_num, topic, inject_pii = task - try: - query = future.result() - queries.append((query_num, query)) - except Exception as e: - # Use fallback on error - if inject_pii: - fallback_query = f"Hi, I'm John Smith (john.smith@email.com) and I need help with {topic}" - else: - fallback_query = f"Can you explain {topic}?" - queries.append((query_num, fallback_query)) - print(f"⚠️ Query {query_num} generation failed, using fallback") + query_num = future_to_task[future][0] + queries.append((query_num, future.result())) completed_count += 1 if completed_count % 100 == 0 or completed_count == num_queries: @@ -303,29 +296,23 @@ def run(self, num_queries): start_time = time.time() - # Execute concurrent requests + # Execute concurrent requests; results are logged in send_single_request with ThreadPoolExecutor(max_workers=self.concurrency) as executor: - futures = { - executor.submit(self.send_single_request, num, query): (num, query) - for num, query in queries - } - - # Wait for all to complete - for future in as_completed(futures): - pass # Results are logged in send_single_request - + for _, query in queries: + executor.submit(self.send_single_request, num_queries, query) + total_duration = time.time() - start_time # Summary print() - print(f"=" * 70) - print(f"βœ… COMPLETE") - print(f"=" * 70) + print("=" * 70) + print("βœ… COMPLETE") + print("=" * 70) print(f"Total time: {total_duration/60:.1f} minutes ({total_duration:.0f}s)") print(f"Successful: {self.successful}/{num_queries} ({100*self.successful/num_queries:.1f}%)") print(f"Failed: {self.failed}/{num_queries} ({100*self.failed/num_queries:.1f}%)") print(f"Average: {total_duration/num_queries:.1f}s per query (with concurrency)") - print(f"=" * 70) + print("=" * 70) def main(): parser = argparse.ArgumentParser(description='Concurrent traffic generator for AI agent testing') diff --git a/tools/traffic_generator.py b/tools/traffic_generator.py index 3509cb3..c118d18 100755 --- a/tools/traffic_generator.py +++ b/tools/traffic_generator.py @@ -2,7 +2,7 @@ """ Simple Traffic Generator with AI -1. Analyze knowledge base for topics +1. Ask Claude for topics from the sample textbook in kb/ 2. Generate queries using random topic/complexity 3. Send to API 4. Get AI feedback on response @@ -44,37 +44,38 @@ def get_user_id(self): self.user_counter += 1 return f"user_{self.session_id}_{self.user_counter}" - def analyze_knowledge_base(self): - """Ask Claude to analyze KB and return topics""" - print("Analyzing knowledge base...") + def generate_topics(self): + """Ask Claude for topics from the sample textbook (Sutton & Barto)""" + print("πŸ“š Generating base topics...") try: response = self.claude.messages.create( - model="claude-3-5-sonnet-latest", + model="claude-haiku-5-5", max_tokens=800, + thinking={"type": "disabled"}, messages=[{ "role": "user", - "content": "List 15 technical topics that users would ask about regarding LaunchDarkly, feature flags, A/B testing, or deployment strategies. Just return a simple list of topics." + "content": "List 15 reinforcement learning topics from the Sutton & Barto textbook. Just return a simple list of topics." }] ) # Parse topics from response topics_text = response.content[0].text - topics = [line.strip().strip('-β€’*123456789.') for line in topics_text.split('\n') if line.strip()] + topics = [line.strip().lstrip('-β€’*0123456789. ') for line in topics_text.split('\n') if line.strip()] topics = [t for t in topics if len(t) > 3][:15] # Clean and limit to 15 if not topics: raise ValueError("No topics extracted") - print(f"Found {len(topics)} topics") + print(f"βœ… Generated {len(topics)} base topics") return topics except Exception as e: - print(f"KB analysis failed, using defaults: {e}") + print(f"❌ Error generating topics, using defaults: {e}") return [ - "feature flags", "A/B testing", "user targeting", - "rollout strategies", "SDK integration", "metrics", - "deployment", "configuration", "debugging" + "Q-learning", "SARSA", "Policy gradients", "Actor-critic methods", + "Temporal difference learning", "Monte Carlo methods", "Dynamic programming", + "Exploration vs exploitation", "Markov Decision Processes", "Value functions" ] def generate_query(self, topic, complexity, inject_pii=False): @@ -107,12 +108,13 @@ def generate_query(self, topic, complexity, inject_pii=False): try: response = self.claude.messages.create( - model="claude-3-5-sonnet-latest", + model="claude-haiku-5-5", max_tokens=150, + thinking={"type": "disabled"}, messages=[{"role": "user", "content": prompt}] ) return response.content[0].text.strip() - except: + except Exception: # Fallback query if inject_pii: pii_templates = { @@ -167,6 +169,7 @@ def send_chat(self, query): def evaluate_response(self, query, response): """Ask Claude to evaluate if user would give feedback""" + # Every Claude call here disables thinking: Haiku 5.5 thinks by default, which uses up these small max_tokens budgets prompt = f"""Based on this Q&A, would a user give feedback? Question: {query[:200]} @@ -177,14 +180,14 @@ def evaluate_response(self, query, response): - negative (poor answer, user would thumbs down) - none (okay answer, user wouldn't bother rating) -Most users don't give feedback unless the answer is notably good or bad.""" +Users give a thumbs up to answers that fully and correctly answer the question, a thumbs down to answers that are wrong, evasive, or ask for information the question already gave, and no rating to answers that only partly help.""" try: response = self.claude.messages.create( - model="claude-3-5-sonnet-latest", + model="claude-haiku-5-5", max_tokens=10, - messages=[{"role": "user", "content": prompt}], - timeout=2 + thinking={"type": "disabled"}, + messages=[{"role": "user", "content": prompt}] ) feedback = response.content[0].text.strip().lower() @@ -195,7 +198,7 @@ def evaluate_response(self, query, response): else: return "none" - except: + except Exception: return "none" # Default to no feedback on error def send_feedback(self, chat_data, query, feedback_type): @@ -216,28 +219,23 @@ def send_feedback(self, chat_data, query, feedback_type): "model": chat_data.get("model", "unknown"), "tool_calls": chat_data.get("tool_calls", []), # Add required tool_calls field "source": "simulated", - "user_context": self.user_context # Add context for LaunchDarkly targeting + "user_context": {**self.user_context, "user": chat_data["user_id"]} # Same context as the chat request }, timeout=10 ) - except: + except Exception: pass # Ignore feedback errors def run(self, num_queries, delay): """Main execution loop""" - print(f"\nπŸš€ DEBUG: Starting {num_queries} queries with {delay}s delay\n") + print(f"\nπŸš€ Starting {num_queries} queries with {delay}s delay\n") - # Step 1: Get topics from knowledge base - print("πŸ” DEBUG: Step 1 - Analyzing knowledge base...") - topics = self.analyze_knowledge_base() - print(f"βœ… DEBUG: Got {len(topics)} topics: {topics[:3]}...") + # Step 1: Get topics from the sample textbook + topics = self.generate_topics() complexities = ["basic", "intermediate", "advanced"] # Step 2: Generate and process queries - print(f"πŸ” DEBUG: Step 2 - Starting loop for {num_queries} queries...") for i in range(num_queries): - print(f"\nπŸ” DEBUG: Loop iteration {i+1}/{num_queries} starting...") - # Random selection topic = random.choice(topics) complexity = random.choice(complexities) @@ -246,36 +244,26 @@ def run(self, num_queries, delay): inject_pii = random.random() < (self.pii_percentage / 100.0) pii_indicator = " [PII]" if inject_pii else "" - print(f"πŸ” DEBUG: Selected topic='{topic}', complexity='{complexity}', inject_pii={inject_pii}") - print(f"\n[{i+1}/{num_queries}] {topic} ({complexity}){pii_indicator}") # Generate query - print("πŸ” DEBUG: Calling generate_query...") query = self.generate_query(topic, complexity, inject_pii) - print(f"βœ… DEBUG: Generated query: {query[:50]}...") print(f" Q: {query[:80]}...") # Add small delay to prevent Claude API rate limiting - print("πŸ” DEBUG: Adding 1s delay before API calls...") time.sleep(1) # Send to API - print("πŸ” DEBUG: Calling send_chat...") chat_data = self.send_chat(query) - print(f"βœ… DEBUG: send_chat returned: success={chat_data['success']}") if chat_data["success"]: print(f" A: {chat_data['response'][:80]}...") # Add small delay before evaluation - print("πŸ” DEBUG: Adding 1s delay before evaluation...") time.sleep(1) # Evaluate response - print("πŸ” DEBUG: Calling evaluate_response...") feedback = self.evaluate_response(query, chat_data["response"]) - print(f"βœ… DEBUG: evaluate_response returned: {feedback}") if feedback == "positive": print(" πŸ‘ Positive feedback") @@ -285,20 +273,14 @@ def run(self, num_queries, delay): print(" 😐 No feedback") # Send feedback to API - print("πŸ” DEBUG: Calling send_feedback...") self.send_feedback(chat_data, query, feedback) - print("βœ… DEBUG: send_feedback completed") else: print(" ❌ API call failed") - print(f"πŸ” DEBUG: Loop iteration {i+1}/{num_queries} completed") - # Delay between requests if delay > 0 and i < num_queries - 1: - print(f"πŸ” DEBUG: Sleeping for {delay}s...") time.sleep(delay) - print(f"\nπŸ” DEBUG: Loop completed, reached end of run() method") print("\nβœ… Complete\n") def main(): @@ -318,4 +300,4 @@ def main(): generator.run(args.queries, args.delay) if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/tools_impl/dynamic_tool_factory.py b/tools_impl/dynamic_tool_factory.py index 899ef2f..2e8063d 100644 --- a/tools_impl/dynamic_tool_factory.py +++ b/tools_impl/dynamic_tool_factory.py @@ -1,49 +1,29 @@ """ Dynamic Tool Factory for LaunchDarkly AI Configuration -Recreates the dynamic tool loading that was lost in the architecture change + +Builds the support agent's tools from the tool definitions in its AI Config. """ from typing import Dict, List, Any, Optional import os +import asyncio +import concurrent.futures +import contextvars from langchain_core.tools import BaseTool from pydantic import BaseModel, Field, create_model -from utils.logger import log_student, log_debug, log_verbose -import json +from utils.logger import log_student, log_debug def extract_tool_configs_from_launchdarkly(config) -> tuple[List[str], Dict[str, Any]]: """ Extract tool configurations from LaunchDarkly AI Config. Returns: (tools_list, tool_configs) - - This restores the functionality that was lost when switching from StateGraph to create_react_agent. """ - tools_list = [] - tool_configs = {} - - # Get tools from the initial config (tools are stable, instructions are dynamic) - if hasattr(config, 'tools') and config.tools: - tools_list = list(config.tools) - - # Try to get tool configurations from config dict structure - try: - config_dict = config.to_dict() - if 'model' in config_dict and 'parameters' in config_dict['model'] and 'tools' in config_dict['model']['parameters']: - tools_data = config_dict['model']['parameters']['tools'] - for tool in tools_data: - if 'name' in tool: - tool_name = tool['name'] - if tool_name not in tools_list: - tools_list.append(tool_name) - # Extract tool parameters/schema from LaunchDarkly - tool_configs[tool_name] = tool.get('parameters', {}) - - log_debug(f"EXTRACTED TOOLS FROM LAUNCHDARKLY: {tools_list}") - if tool_configs: - log_verbose(f" TOOL CONFIGS FROM LAUNCHDARKLY: {tool_configs}") - - except Exception as e: - log_debug(f"Error extracting tool configs from LaunchDarkly: {e}") - pass # Fallback to just the tools list and defaults + tool_configs = {tool['name']: tool.get('parameters', {}) for tool in config.parameters.get('tools', [])} + tools_list = list(tool_configs) + + log_debug(f"EXTRACTED TOOLS FROM LAUNCHDARKLY: {tools_list}") + if tool_configs: + log_debug(f" TOOL CONFIGS FROM LAUNCHDARKLY: {tool_configs}") return tools_list, tool_configs @@ -57,35 +37,19 @@ def create_dynamic_tool_instance(tool_name: str, tool_config: Dict[str, Any]) -> log_debug(f"Creating dynamic tool: {tool_name}") if tool_name == "search_v1": - return _create_dynamic_search_v1(tool_config) + from tools_impl.search_v1 import SearchToolV1 + return SearchToolV1() elif tool_name == "search_v2": return _create_dynamic_search_v2(tool_config) elif tool_name == "reranking": return _create_dynamic_reranking_tool(tool_config) - elif tool_name in ["arxiv_search", "semantic_scholar"]: - return _create_dynamic_mcp_tool(tool_name, tool_config) + elif tool_name in ["arxiv_search", "openalex_search"]: + return _create_dynamic_mcp_tool(tool_name) else: log_debug(f"❓ UNKNOWN TOOL: {tool_name}") return None -def _create_dynamic_search_v1(tool_config: Dict[str, Any]) -> BaseTool: - """Create search_v1 tool with LaunchDarkly configuration""" - from tools_impl.search_v1 import SearchToolV1 - - # Create base tool instance - tool = SearchToolV1() - - # Apply LaunchDarkly configuration if available - if tool_config and 'properties' in tool_config: - log_debug(f"SEARCH_V1: Applying LaunchDarkly config") - # Could override defaults here based on LaunchDarkly config - # For now, just log that config is available - pass - - return tool - - def _create_dynamic_search_v2(tool_config: Dict[str, Any]) -> BaseTool: """Create search_v2 tool with LaunchDarkly configuration""" @@ -98,29 +62,27 @@ def _create_dynamic_search_v2(tool_config: Dict[str, Any]) -> BaseTool: field_definitions = {} for field_name, field_config in properties.items(): - field_type = str # Default to string - field_default = None + field_type: Any = str # Default to string + field_default: Any = None field_description = field_config.get('description', '') # Map LaunchDarkly JSON schema types to Python types - if field_config.get('type') == 'number': + if field_config.get('type') in ('number', 'integer'): field_type = int field_default = 3 # Default for top_k - elif field_config.get('type') == 'string': - field_type = str # Create Pydantic field if field_name in tool_config.get('required', []): field_definitions[field_name] = (field_type, Field(description=field_description)) else: - field_definitions[field_name] = (field_type, Field(default=field_default, description=field_description)) + field_definitions[field_name] = (Optional[field_type], Field(default=field_default, description=field_description)) # Create dynamic Pydantic model DynamicSearchV2Input = create_model('DynamicSearchV2Input', **field_definitions) else: # Fallback to minimal schema - log_debug(f"SEARCH_V2: No LaunchDarkly config found, using minimal schema") + log_debug("SEARCH_V2: No LaunchDarkly config found, using minimal schema") class DynamicSearchV2Input(BaseModel): query: str top_k: Optional[int] = 3 @@ -131,11 +93,9 @@ class DynamicSearchToolV2(BaseTool): description: str = "Semantic search using vector embeddings" args_schema: type[BaseModel] = DynamicSearchV2Input - def _run(self, query: str, top_k: int = 3) -> str: - # Import and delegate to actual implementation + def _run(self, query: str, top_k: Optional[int] = 3, **kwargs: Any) -> str: from tools_impl.search_v2 import SearchToolV2 - actual_tool = SearchToolV2() - return actual_tool._run(query, top_k) + return SearchToolV2()._run(query, 3 if top_k is None else top_k, **kwargs) return DynamicSearchToolV2() @@ -146,34 +106,30 @@ def _create_dynamic_reranking_tool(tool_config: Dict[str, Any]) -> BaseTool: # Create dynamic input schema based on LaunchDarkly tool definition if tool_config and 'properties' in tool_config: properties = tool_config['properties'] + required_fields = set(tool_config.get('required', [])) log_debug(f"RERANKING: Creating dynamic schema from LaunchDarkly: {properties}") # Build Pydantic field definitions from LaunchDarkly schema field_definitions = {} for field_name, field_config in properties.items(): + # Map LaunchDarkly types to Python types; results can be strings or dicts from search_v2 + field_type: Any = List[Any] if field_config.get('type') == 'array' else str field_description = field_config.get('description', '') - - # Map LaunchDarkly types to Python types - if field_config.get('type') == 'array': - field_type = List[Dict[str, Any]] # For results array - elif field_config.get('type') == 'string': - field_type = str + if field_name in required_fields: + field_definitions[field_name] = (field_type, Field(description=field_description)) else: - field_type = str # Default - - # Create Pydantic field - field_definitions[field_name] = (field_type, Field(description=field_description)) + field_definitions[field_name] = (Optional[field_type], Field(default=None, description=field_description)) # Create dynamic Pydantic model DynamicRerankingInput = create_model('DynamicRerankingInput', **field_definitions) else: # Fallback to minimal schema matching LaunchDarkly - log_debug(f"RERANKING: No LaunchDarkly config found, using minimal schema") + log_debug("RERANKING: No LaunchDarkly config found, using minimal schema") class DynamicRerankingInput(BaseModel): query: str - results: Optional[List[Dict[str, Any]]] = None + results: Optional[List[Any]] = None # Create dynamic tool class class DynamicRerankingTool(BaseTool): @@ -181,21 +137,15 @@ class DynamicRerankingTool(BaseTool): description: str = "Reorders results by relevance using BM25 algorithm" args_schema: type[BaseModel] = DynamicRerankingInput - def _run(self, query: str, results: List[Dict[str, Any]] = None, **kwargs) -> str: - # Import and delegate to actual implementation + def _run(self, query: str, results: Optional[List[Any]] = None, **kwargs: Any) -> str: from tools_impl.reranking import RerankingTool - actual_tool = RerankingTool() - return actual_tool._run(query, results, **kwargs) + return RerankingTool()._run(query, results, **kwargs) return DynamicRerankingTool() def _create_mcp_tool_wrapper(mcp_tool, ld_name: str): """Create wrapper for MCP tool that properly handles async/sync execution""" - from langchain.tools import BaseTool - from typing import Any - import asyncio - import concurrent.futures class MCPToolWrapper(BaseTool): name: str = ld_name # Use LaunchDarkly name @@ -207,151 +157,68 @@ def __init__(self, mcp_tool, ld_name): super().__init__() object.__setattr__(self, 'wrapped_tool', mcp_tool) object.__setattr__(self, 'name', ld_name) - # Copy the args_schema from the wrapped MCP tool - if hasattr(mcp_tool, 'args_schema'): - object.__setattr__(self, 'args_schema', mcp_tool.args_schema) + object.__setattr__(self, 'args_schema', mcp_tool.args_schema) async def _arun(self, config=None, **kwargs) -> str: """Execute the wrapped MCP tool asynchronously.""" try: # Handle nested kwargs structure from MCP tools if 'kwargs' in kwargs and isinstance(kwargs['kwargs'], dict): - actual_kwargs = kwargs['kwargs'] - else: - actual_kwargs = kwargs - - print(f"πŸ” MCP TOOL {self.name} received args: {actual_kwargs}") - log_debug(f"MCP TOOL {self.name} received args: {actual_kwargs}") - - # Use await to call the async tool method - if hasattr(self.wrapped_tool, '_arun'): - result = await self.wrapped_tool._arun(config=config, **actual_kwargs) - elif hasattr(self.wrapped_tool, 'ainvoke'): - # MCP tools expect flat kwargs, not nested in config - result = await self.wrapped_tool.ainvoke(actual_kwargs) - elif hasattr(self.wrapped_tool, 'invoke'): - # Some tools might be sync, run in executor - with concurrent.futures.ThreadPoolExecutor() as executor: - result = await asyncio.get_event_loop().run_in_executor( - executor, lambda: self.wrapped_tool.invoke(actual_kwargs) - ) - else: - raise ValueError(f"MCP tool {self.name} has no callable method") + kwargs = kwargs['kwargs'] + print(f"πŸ” MCP TOOL {self.name} received args: {kwargs}") + result = await self.wrapped_tool._arun(config=config, **kwargs) return str(result) except Exception as e: import traceback - error_details = traceback.format_exc() - log_debug(f"MCP TOOL ASYNC ERROR in {self.name}: {e}") - log_debug(f"MCP TOOL TRACEBACK: {error_details}") + log_debug(f"MCP TOOL TRACEBACK: {traceback.format_exc()}") print(f"⚠️ MCP TOOL ERROR ({self.name}): {e}") return f"MCP tool error: {str(e)}" def _run(self, **kwargs) -> str: - """Execute the wrapped MCP tool synchronously.""" + """Execute the wrapped MCP tool synchronously (MCP tools are async-only).""" try: - # Handle nested kwargs structure - if 'kwargs' in kwargs and isinstance(kwargs['kwargs'], dict): - actual_kwargs = kwargs['kwargs'] - else: - actual_kwargs = kwargs - - print(f"πŸ” MCP TOOL {self.name} SYNC received args: {actual_kwargs}") - log_debug(f"MCP TOOL {self.name} SYNC received args: {actual_kwargs}") - - # MCP tools are async-only, so always use async execution - try: - loop = asyncio.get_event_loop() - if loop.is_running(): - # Create new loop for sync execution in thread - with concurrent.futures.ThreadPoolExecutor() as executor: - future = executor.submit(asyncio.run, self._arun(**actual_kwargs)) - result = future.result(timeout=30) - else: - result = loop.run_until_complete(self._arun(**actual_kwargs)) - except RuntimeError: - # No event loop, create one - result = asyncio.run(self._arun(**actual_kwargs)) - - return str(result) - - except Exception as e: - import traceback - error_details = traceback.format_exc() - log_debug(f"MCP TOOL SYNC ERROR in {self.name}: {e}") - log_debug(f"MCP TOOL TRACEBACK: {error_details}") - print(f"⚠️ MCP TOOL ERROR ({self.name}): {e}") - return f"MCP tool error: {str(e)}" + asyncio.get_running_loop() + except RuntimeError: + return asyncio.run(self._arun(**kwargs)) + # Already inside an event loop, so run in a fresh loop on another thread + with concurrent.futures.ThreadPoolExecutor() as executor: + return executor.submit(asyncio.run, self._arun(**kwargs)).result(timeout=30) return MCPToolWrapper(mcp_tool, ld_name) -def _create_dynamic_mcp_tool(tool_name: str, tool_config: Dict[str, Any]) -> Optional[BaseTool]: - """Create MCP tool with LaunchDarkly configuration using working wrapper pattern""" +def _create_dynamic_mcp_tool(tool_name: str) -> Optional[BaseTool]: + """Create an MCP tool, loading the MCP servers on first use""" # Disable MCP tools in CI safe mode to reduce flakiness while preserving core functionality if os.getenv("CI_SAFE_MODE", "").lower() in {"1", "true", "yes"}: log_debug(f"CI_SAFE_MODE enabled: skipping MCP tool {tool_name}") return None - try: - from tools_impl.mcp_research_tools import MCPResearchTools - import asyncio - import concurrent.futures - - def initialize_mcp_tools(): - """Initialize MCP tools in a separate thread with new event loop""" - try: - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - - mcp_client = MCPResearchTools() - result = loop.run_until_complete(mcp_client.initialize()) - - available_mcp_tools = [] - if hasattr(mcp_client, 'tools') and mcp_client.tools: - for tool_name_key, tool_instance in mcp_client.tools.items(): - available_mcp_tools.append(tool_instance) - - return available_mcp_tools - - except Exception as e: - log_debug(f"MCP initialization error: {e}") - return [] - finally: - try: - loop.close() - except: - pass - - # Run MCP initialization in thread with timeout - with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor: - future = executor.submit(initialize_mcp_tools) - try: - mcp_tools = future.result(timeout=30) # 30 second timeout - - # Map LaunchDarkly tool names to actual MCP tool names - ld_to_mcp_mapping = { - "arxiv_search": "search_papers", - "semantic_scholar": "search_semantic_scholar" - } - - mcp_tool_name = ld_to_mcp_mapping.get(tool_name) - if mcp_tool_name: - # Find matching MCP tool - for mcp_tool in mcp_tools: - if hasattr(mcp_tool, 'name') and mcp_tool_name in mcp_tool.name.lower(): - # Create wrapper to handle async execution properly - wrapped_tool = _create_mcp_tool_wrapper(mcp_tool, tool_name) - log_debug(f"MCP TOOL CREATED: {tool_name} -> {mcp_tool_name}") - return wrapped_tool - - except concurrent.futures.TimeoutError: - log_debug(f"MCP TIMEOUT: {tool_name} not available") - except ImportError: - log_debug(f"MCP IMPORT ERROR: {tool_name} not available") - - return None + from tools_impl.mcp_research_tools import MCPResearchTools + + def initialize_mcp_tools(): + """Initialize MCP tools in a separate thread with new event loop""" + mcp_client = MCPResearchTools() + try: + asyncio.run(mcp_client.initialize()) + except Exception as e: + log_debug(f"MCP initialization error: {e}") + return mcp_client.tools + + # Run MCP initialization in thread with timeout; copy_context keeps its output in the request's console logs + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor: + try: + mcp_tool = executor.submit(contextvars.copy_context().run, initialize_mcp_tools).result(timeout=30).get(tool_name) + except concurrent.futures.TimeoutError: + log_debug(f"MCP TIMEOUT: {tool_name} not available") + return None + + if mcp_tool is None: + return None + log_debug(f"MCP TOOL CREATED: {tool_name} -> {mcp_tool.name}") + return _create_mcp_tool_wrapper(mcp_tool, tool_name) def create_dynamic_tools_from_launchdarkly(config) -> List[BaseTool]: @@ -361,18 +228,10 @@ def create_dynamic_tools_from_launchdarkly(config) -> List[BaseTool]: """ tools_list, tool_configs = extract_tool_configs_from_launchdarkly(config) - # In CI safe mode, skip network-dependent MCP tools while keeping local tools - if os.getenv("CI_SAFE_MODE", "").lower() in {"1", "true", "yes"}: - original = list(tools_list) - tools_list = [t for t in tools_list if t not in ["arxiv_search", "semantic_scholar"]] - if original != tools_list: - log_debug(f"CI_SAFE_MODE: filtered tools {set(original) - set(tools_list)}") - available_tools = [] for tool_name in tools_list: - tool_config = tool_configs.get(tool_name, {}) - tool_instance = create_dynamic_tool_instance(tool_name, tool_config) + tool_instance = create_dynamic_tool_instance(tool_name, tool_configs[tool_name]) if tool_instance: available_tools.append(tool_instance) @@ -382,4 +241,4 @@ def create_dynamic_tools_from_launchdarkly(config) -> List[BaseTool]: log_student(f"DYNAMIC TOOLS LOADED: {[tool.name for tool in available_tools]}") - return available_tools \ No newline at end of file + return available_tools diff --git a/tools_impl/mcp_research_tools.py b/tools_impl/mcp_research_tools.py index 3d0a4fa..9c50e09 100644 --- a/tools_impl/mcp_research_tools.py +++ b/tools_impl/mcp_research_tools.py @@ -1,185 +1,97 @@ -from langchain.tools import BaseTool -from langchain_mcp_adapters.client import MultiServerMCPClient +from langchain.tools import BaseTool, StructuredTool from langchain_mcp_adapters.tools import load_mcp_tools -from langchain_mcp_adapters.sessions import StdioConnection -import asyncio -from typing import List, Optional -import logging -import time -import random - -logger = logging.getLogger(__name__) +from tools_impl.openalex_auth import OPENALEX_MCP_URL, TOKEN_FILE, openalex_auth +import os +import shutil +import threading +import traceback # Process-lifetime singleton to prevent repeated MCP server startup _MCP_SINGLETON = None -_MCP_LOCK = asyncio.Lock() +# A thread lock, because each initialization runs on its own event loop +_MCP_LOCK = threading.Lock() + + +def _query_only(search_works: BaseTool, connection: dict) -> BaseTool: + """OpenAlex search_works takes dozens of optional filters, and models fill in + every one, which the server rejects. Expose only the query.""" + async def search(query: str) -> str: + # The OAuth provider reads the token file only once, so give each call a fresh + # one; reading the file is what refreshes expired tokens. + connection["auth"] = openalex_auth() + return await search_works.ainvoke({"query": query, "limit": 5}) + return StructuredTool.from_function( + coroutine=search, + name=search_works.name, + description="Search OpenAlex for scholarly works. Returns titles, authors, years, and citation counts.", + ) class MCPResearchTools: """MCP Research Tools integration using real MCP servers with process lifetime reuse""" - + def __init__(self): - self.client = None self.tools = {} - self._initialized = False - + async def initialize(self): - """Initialize MCP client with research servers using process lifetime reuse""" + """Load tools from the configured research servers, once per process""" global _MCP_SINGLETON - - async with _MCP_LOCK: + + with _MCP_LOCK: if _MCP_SINGLETON is not None: - # Reuse existing singleton - self.client = _MCP_SINGLETON.client self.tools = _MCP_SINGLETON.tools - self._initialized = True print(f"πŸ”„ MCP: Reusing singleton with {len(self.tools)} tools") return - - print(" MCP: Initializing process-lifetime singleton...") - - try: - # Configure MCP servers for research using environment variables - import os - - server_configs = {} - - # ArXiv MCP Server - only add if path is configured - arxiv_path = os.getenv('ARXIV_MCP_SERVER_PATH') - if arxiv_path and os.path.exists(arxiv_path): - server_configs["arxiv"] = { - "command": arxiv_path, - "args": ["--storage-path", "/tmp/arxiv-papers"] - } - print(f" MCP: ArXiv server configured at {arxiv_path}") - - # Semantic Scholar MCP Server - only add if path is configured - semantic_path = os.getenv('SEMANTIC_SCHOLAR_SERVER_PATH') - if semantic_path and os.path.exists(semantic_path): - server_configs["semanticscholar"] = { - "command": "python", - "args": [semantic_path] - } - print(f" MCP: Semantic Scholar server configured at {semantic_path}") - - # Try to initialize with available servers - available_configs = {} - for name, config in server_configs.items(): - try: - # Test if server is available - available_configs[name] = config - logger.info(f"MCP server '{name}' configured") - except Exception as e: - logger.warning(f"MCP server '{name}' not available: {e}") - - if available_configs: - # Initialize individual MCP connections and collect tools - langchain_tools = [] - - # Load tools from each server individually - for server_name, config in available_configs.items(): - try: - # Create connection for this server - add transport to config - connection_config = { - **config, - "transport": "stdio" - } - connection = StdioConnection(connection_config) - - # Load tools from this server - server_tools = await load_mcp_tools(None, connection=connection) - langchain_tools.extend(server_tools) - # print(f"DEBUG: Loaded {len(server_tools)} tools from {server_name} MCP server") - - except Exception as e: - print(f" ERROR: Failed to load tools from {server_name}: {e}") - import traceback - print(f" TRACEBACK: {traceback.format_exc()}") - continue - - # Organize tools by type - map actual MCP tools to our expected names - for tool in langchain_tools: - tool_name = tool.name.lower() - # print(f"DEBUG: Found MCP tool: {tool.name} ({tool.description[:100]}...)") - - # Map ArXiv tools - use search_papers as the primary tool for arxiv_search - if "search_papers" in tool_name or "arxiv" in tool_name: - self.tools["arxiv_search"] = tool - # Store all ArXiv tools under their original names too - self.tools[tool.name] = tool - # Map Semantic Scholar tools - use search_semantic_scholar as primary - elif "semantic_scholar" in tool_name: - if "search_semantic_scholar" in tool_name: - self.tools["semantic_scholar"] = tool - # Store all Semantic Scholar tools under their original names - self.tools[tool.name] = tool - - # print(f"DEBUG: Initialized MCP tools: {list(self.tools.keys())}") - - # Store singleton for process lifetime reuse - async with _MCP_LOCK: - if _MCP_SINGLETON is None: - _MCP_SINGLETON = self - print(" MCP: Singleton initialized for process lifetime") - - except Exception as e: - # print(f"DEBUG: Failed to initialize MCP client: {e}") - self.client = None - - self._initialized = True - # print("DEBUG: MCPResearchTools.initialize() completed") - - def get_tool(self, tool_name: str) -> Optional[BaseTool]: - """Get a specific MCP tool""" - return self.tools.get(tool_name) - - def get_available_tools(self) -> List[str]: - """Get list of available MCP tool names""" - return list(self.tools.keys()) - - async def close(self): - """Clean up MCP client""" - if self.client: - await self.client.close() - - -# Simplified for demo - no singleton caching -async def get_mcp_research_tools() -> MCPResearchTools: - """Create and initialize MCP research tools instance""" - # print("DEBUG: Creating new MCPResearchTools instance") - mcp_research_tools = MCPResearchTools() - # print("DEBUG: Initializing MCP tools...") - await mcp_research_tools.initialize() - # print("DEBUG: MCP initialization completed") - return mcp_research_tools - - -# MCP-only implementation - no fallback tools -async def get_research_tools() -> List[BaseTool]: - """Get MCP research tools - requires MCP servers to be installed""" - # print("DEBUG: get_research_tools called") - tools = [] - - try: - # print("DEBUG: Getting MCP research tools instance") - mcp_tools = await get_mcp_research_tools() - available_tools = mcp_tools.get_available_tools() - # print(f"DEBUG: Available MCP tools: {available_tools}") - - # Only return real MCP tools - no fallbacks - if "arxiv_search" in available_tools: - tools.append(mcp_tools.get_tool("arxiv_search")) - print(" Added ArXiv MCP tool") - - if "semantic_scholar" in available_tools: - tools.append(mcp_tools.get_tool("semantic_scholar")) - print(" Added Semantic Scholar MCP tool") - - if not tools: - print("No MCP research tools available. Install MCP servers: npm install -g @michaellatman/mcp-server-arxiv") - - except Exception as e: - print(f" MCP tools initialization failed: {e}") - print("Install MCP servers to enable research tools: npm install -g @michaellatman/mcp-server-arxiv") - - # print(f"DEBUG: Returning {len(tools)} MCP tools") - return tools \ No newline at end of file + + print(" MCP: Initializing process-lifetime singleton...") + + server_configs = {} + + # ArXiv MCP Server - auto-discover from PATH (uv tool install arxiv-mcp-server) or ARXIV_MCP_SERVER_PATH + arxiv_path = os.getenv('ARXIV_MCP_SERVER_PATH') or shutil.which('arxiv-mcp-server') + if arxiv_path and os.path.exists(arxiv_path): + server_configs["arxiv"] = { + "transport": "stdio", + "command": arxiv_path, + "args": ["--storage-path", "/tmp/arxiv-papers"] + } + print(f" MCP: ArXiv server configured at {arxiv_path}") + + # OpenAlex MCP Server - only add after running tools_impl/openalex_auth.py + if TOKEN_FILE.exists(): + server_configs["openalex"] = { + "transport": "streamable_http", + "url": OPENALEX_MCP_URL, + "auth": openalex_auth() + } + print(" MCP: OpenAlex server configured") + + if not server_configs: + return + + # Load tools from each server individually, so one failing server doesn't block the other + all_loaded = True + for server_name, config in server_configs.items(): + try: + server_tools = await load_mcp_tools(None, connection=config) + except Exception as e: + all_loaded = False + print(f" ERROR: Failed to load tools from {server_name}: {e}") + print(f" TRACEBACK: {traceback.format_exc()}") + continue + + # Map the MCP tools we use to their LaunchDarkly tool names + for tool in server_tools: + if tool.name == "search_papers": + self.tools["arxiv_search"] = tool + elif tool.name == "search_works": + self.tools["openalex_search"] = _query_only(tool, config) + + # A server that failed to load is retried on the next request instead of being cached as missing + if not all_loaded: + return + + # Store singleton for process lifetime reuse + with _MCP_LOCK: + if _MCP_SINGLETON is None: + _MCP_SINGLETON = self + print(" MCP: Singleton initialized for process lifetime") diff --git a/tools_impl/mcp_runtime.py b/tools_impl/mcp_runtime.py deleted file mode 100644 index feace2e..0000000 --- a/tools_impl/mcp_runtime.py +++ /dev/null @@ -1,91 +0,0 @@ -from __future__ import annotations - -import asyncio -import threading -from typing import Any, Dict, Optional -import logging - -logger = logging.getLogger(__name__) - -# Optional: if MCP uses httpx/aiohttp, wire a shared client into MCPResearchTools -try: - import httpx -except ImportError: - httpx = None - -class _LoopRunner: - def __init__(self) -> None: - self._loop = asyncio.new_event_loop() - self._thread = threading.Thread(target=self._run, name="mcp-loop", daemon=True) - self._thread.start() - - def _run(self): - asyncio.set_event_loop(self._loop) - self._loop.run_forever() - - def call(self, coro, timeout: Optional[float] = None): - fut = asyncio.run_coroutine_threadsafe(coro, self._loop) - return fut.result(timeout) - - @property - def loop(self): - return self._loop - -class MCPRuntime: - """Process-wide MCP runtime: one loop, one MCP client, reusable tools.""" - _instance: Optional["MCPRuntime"] = None - _lock = threading.Lock() - - def __init__(self): - from tools_impl.mcp_research_tools import MCPResearchTools # local import - - logger.info(" Initializing process-wide MCP runtime...") - self.loop_runner = _LoopRunner() - - # Optional shared HTTP client to pass into MCPResearchTools if supported. - shared_http: Optional[Any] = None - if httpx is not None: - try: - shared_http = httpx.AsyncClient( - # Skip http2 to avoid dependency issues - limits=httpx.Limits(max_keepalive_connections=16, max_connections=64), - timeout=httpx.Timeout(30.0, connect=10.0), - ) - logger.info(" Created shared HTTP client for connection pooling") - except Exception as e: - logger.warning(" Could not create shared HTTP client: %s", e) - shared_http = None - - async def _init(): - try: - # Try to pass shared HTTP client if MCPResearchTools supports it - try: - client = MCPResearchTools(http_client=shared_http) if shared_http else MCPResearchTools() - except TypeError: - # Fallback if MCPResearchTools doesn't accept http_client parameter - client = MCPResearchTools() - - await client.initialize() - logger.info(" MCP client initialized successfully") - return client - except Exception as e: - logger.error(" Failed to initialize MCP client: %s", e) - raise - - try: - self.client = self.loop_runner.call(_init(), timeout=60) - self.tools: Dict[str, Any] = getattr(self.client, "tools", {}) or {} - logger.info(" MCPRuntime initialized with %d tools: %s", len(self.tools), list(self.tools.keys())) - except Exception as e: - logger.error(" MCPRuntime initialization failed: %s", e) - self.client = None - self.tools = {} - - @classmethod - def instance(cls) -> "MCPRuntime": - if cls._instance is not None: - return cls._instance - with cls._lock: - if cls._instance is None: - cls._instance = MCPRuntime() - return cls._instance \ No newline at end of file diff --git a/tools_impl/openalex_auth.py b/tools_impl/openalex_auth.py new file mode 100644 index 0000000..e9d89b8 --- /dev/null +++ b/tools_impl/openalex_auth.py @@ -0,0 +1,136 @@ +"""Sign in to the OpenAlex MCP server. + +The OpenAlex MCP server only accepts OAuth, so sign in once with a free +OpenAlex account: + + uv run python tools_impl/openalex_auth.py + +Tokens are saved to .openalex_tokens.json and refreshed automatically after that. +""" +import asyncio +import json +import os +import time +import webbrowser +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path +from urllib.parse import parse_qs, urlparse + +import httpx +from mcp.client.auth import OAuthClientProvider +from mcp.shared.auth import OAuthClientInformationFull, OAuthClientMetadata, OAuthToken + +OPENALEX_MCP_URL = "https://mcp.openalex.org/mcp" +TOKEN_ENDPOINT = "https://mcp.openalex.org/oauth/token" +TOKEN_FILE = Path(__file__).resolve().parent.parent / ".openalex_tokens.json" +CALLBACK_PORT = 3030 +# Concurrent requests must not refresh at once, or a reused refresh token can be rejected +_refresh_lock = asyncio.Lock() + + +class FileTokenStorage: + """Keeps the OAuth client registration and tokens in TOKEN_FILE.""" + + def _read(self) -> dict: + return json.loads(TOKEN_FILE.read_text()) if TOKEN_FILE.exists() else {} + + def _write(self, key: str, value) -> None: + data = self._read() + data[key] = value.model_dump(mode="json") + if key == "tokens": + data["expires_at"] = time.time() + (value.expires_in or 3600) - 60 + # Created owner-only, so the tokens are never readable by other users + fd = os.open(TOKEN_FILE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + os.fchmod(fd, 0o600) # the mode above only applies when the file is new + with os.fdopen(fd, "w") as f: + f.write(json.dumps(data)) + + async def get_tokens(self): + async with _refresh_lock: + data = self._read() + if "tokens" not in data: + return None + # The MCP client doesn't know when stored tokens expire, so refresh them here + if time.time() > data.get("expires_at", 0): + async with httpx.AsyncClient() as client: + response = await client.post(TOKEN_ENDPOINT, data={ + "grant_type": "refresh_token", + "refresh_token": data["tokens"]["refresh_token"], + "client_id": data["client_info"]["client_id"], + "resource": OPENALEX_MCP_URL, + }) + response.raise_for_status() + tokens = OAuthToken.model_validate(response.json()) + # A refresh response may omit the refresh token, which means keep using the old one + tokens.refresh_token = tokens.refresh_token or data["tokens"]["refresh_token"] + await self.set_tokens(tokens) + return tokens + return OAuthToken.model_validate(data["tokens"]) + + async def set_tokens(self, tokens) -> None: + self._write("tokens", tokens) + + async def get_client_info(self): + info = self._read().get("client_info") + return OAuthClientInformationFull.model_validate(info) if info else None + + async def set_client_info(self, client_info) -> None: + self._write("client_info", client_info) + + +def _wait_for_callback() -> tuple[str, str | None]: + """Serve one request on the redirect URI and return the code and state.""" + result = {} + + class Handler(BaseHTTPRequestHandler): + def do_GET(self): + query = parse_qs(urlparse(self.path).query) + result["code"] = query.get("code", [""])[0] + result["state"] = query.get("state", [None])[0] + self.send_response(200) + self.end_headers() + self.wfile.write(b"Signed in to OpenAlex. You can close this tab.") + + def log_message(self, *args): + pass + + HTTPServer(("localhost", CALLBACK_PORT), Handler).handle_request() + return result["code"], result["state"] + + +def openalex_auth(interactive: bool = False) -> OAuthClientProvider: + """OAuth for the OpenAlex MCP connection. Only the sign-in script opens a browser.""" + + async def redirect(authorization_url: str) -> None: + if not interactive: + raise RuntimeError("OpenAlex sign-in required: run `uv run python tools_impl/openalex_auth.py`") + print(f"Opening {authorization_url}") + webbrowser.open(authorization_url) + + async def callback() -> tuple[str, str | None]: + return await asyncio.to_thread(_wait_for_callback) + + return OAuthClientProvider( + server_url=OPENALEX_MCP_URL, + client_metadata=OAuthClientMetadata( + client_name="LaunchDarkly multi-agent tutorial", + redirect_uris=[f"http://localhost:{CALLBACK_PORT}/callback"], + token_endpoint_auth_method="none", + ), + storage=FileTokenStorage(), + redirect_handler=redirect, + callback_handler=callback, + ) + + +async def main(): + from langchain_mcp_adapters.tools import load_mcp_tools + + tools = await load_mcp_tools(None, connection={ + "transport": "streamable_http", "url": OPENALEX_MCP_URL, "auth": openalex_auth(interactive=True), + }) + print(f"Signed in. OpenAlex tools: {[tool.name for tool in tools]}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/tools_impl/redaction.py b/tools_impl/redaction.py deleted file mode 100644 index 65caed7..0000000 --- a/tools_impl/redaction.py +++ /dev/null @@ -1,21 +0,0 @@ -from langchain.tools import BaseTool -import re - -class RedactionTool(BaseTool): - name: str = "pii_redaction" - description: str = "Redact personally identifiable information from text" - - def _run(self, text: str) -> str: - # Simple PII redaction patterns - redacted = text - - # Redact email addresses - redacted = re.sub(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', '[EMAIL_REDACTED]', redacted) - - # Redact phone numbers (basic patterns) - redacted = re.sub(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b', '[PHONE_REDACTED]', redacted) - - # Redact SSN patterns - redacted = re.sub(r'\b\d{3}-\d{2}-\d{4}\b', '[SSN_REDACTED]', redacted) - - return f"Redacted text: {redacted}" \ No newline at end of file diff --git a/tools_impl/reranking.py b/tools_impl/reranking.py index 7a6f5e9..70addbb 100644 --- a/tools_impl/reranking.py +++ b/tools_impl/reranking.py @@ -1,9 +1,8 @@ from langchain_core.tools import BaseTool from typing import List, Dict, Any, Optional from rank_bm25 import BM25Okapi -from pydantic import BaseModel, Field +from pydantic import BaseModel import re -import json class RerankingInput(BaseModel): query: str @@ -13,124 +12,61 @@ class RerankingTool(BaseTool): name: str = "reranking" description: str = "Reorders results by relevance using BM25 algorithm" args_schema: type[BaseModel] = RerankingInput - + def _tokenize(self, text: str) -> List[str]: """Simple tokenization for BM25""" # Remove punctuation and convert to lowercase text = re.sub(r'[^\w\s]', ' ', text.lower()) - # Split on whitespace and filter empty strings - return [token for token in text.split() if token.strip()] - - def _parse_search_results_from_messages(self, kwargs) -> List[Dict[str, Any]]: - """Parse search_v2 results from ToolMessages when LLM doesn't extract them directly""" - try: - # Try to get messages from various possible kwargs keys - messages = kwargs.get('messages', []) or kwargs.get('chat_history', []) - - # Look for most recent search_v2 ToolMessage in reverse order - for message in reversed(messages): - if hasattr(message, 'content') and isinstance(message.content, str): - content = message.content - # Look for JSON block in search_v2 output - if '```json' in content and 'items' in content: - try: - # Extract JSON from fenced code block - json_start = content.find('```json') + 7 - json_end = content.find('```', json_start) - if json_end > json_start: - json_str = content[json_start:json_end].strip() - search_data = json.loads(json_str) - if isinstance(search_data, dict) and 'items' in search_data: - return search_data['items'] - except (json.JSONDecodeError, KeyError, IndexError): - continue - - return [] - except Exception: - return [] - - - + return text.split() def _run(self, query: str, results: List[Dict[str, Any]] = None, **kwargs) -> str: - # Handle LLM-mediated tool chaining: LLM should extract results from search_v2 ToolMessage - if results is None or not results: - # Fallback: parse recent messages to find search_v2 JSON results - items = self._parse_search_results_from_messages(kwargs) - if not items: - return f"No search results found. Please run search_v2 with query '{query}' first." - else: - # LLM successfully extracted and passed results directly - items = results - - # Validate inputs - if not query: - return "ERROR: `query` parameter is required." + # The LLM chains the tools: it passes the search_v2 results it received as `results` + if not results: + return f"No search results found. Please run search_v2 with query '{query}' first." + items = results - if not isinstance(items, list) or not items: - return "ERROR: `results` must be a non-empty list of search result items from search_v2." - # Extract text content from each item docs = [] for item in items: if isinstance(item, dict) and 'text' in item: docs.append(item['text']) - elif isinstance(item, str): - docs.append(item) else: docs.append(str(item)) - + if len(docs) == 1: return f"Single result (no reranking needed):\n[BM25: N/A] {docs[0]}" - + try: - # Tokenize all documents for BM25 tokenized_docs = [self._tokenize(doc) for doc in docs] - - # Create BM25 model bm25 = BM25Okapi(tokenized_docs) - - # Tokenize query query_tokens = self._tokenize(query) - - # Get BM25 scores for all documents scores = bm25.get_scores(query_tokens) # Handle small corpus issue: if all scores are 0, use simple term frequency scoring if all(score == 0.0 for score in scores): - # Fallback: simple term frequency scoring for small corpora - scores = [] - for doc_tokens in tokenized_docs: - # Count query token matches in document - term_freq_score = sum(1 for token in query_tokens if token in doc_tokens) - # Normalize by document length to favor more focused documents - normalized_score = term_freq_score / len(doc_tokens) if doc_tokens else 0 - scores.append(normalized_score) - scores = [float(s) for s in scores] # Ensure float type + # Count query token matches, normalized by document length to favor focused documents + scores = [ + sum(1 for token in query_tokens if token in doc_tokens) / len(doc_tokens) if doc_tokens else 0.0 + for doc_tokens in tokenized_docs + ] - # Pair items with their scores - item_scores = list(zip(items, scores)) + # Sort items by score (descending) + item_scores = sorted(zip(items, scores), key=lambda x: x[1], reverse=True) - # Sort by score (descending) - item_scores.sort(key=lambda x: x[1], reverse=True) - # Format results with scores reranked_results = [] for i, (item, score) in enumerate(item_scores, 1): if isinstance(item, dict): text = item.get('text', str(item)) orig_score = item.get('score', 'N/A') - metadata = item.get('metadata', {}) reranked_results.append( f"{i}. [BM25: {score:.3f}, Orig: {orig_score}] {text}" ) else: reranked_results.append(f"{i}. [BM25: {score:.3f}] {item}") - - result = f"BM25 reranked results for '{query}':\n\n" + '\n\n'.join(reranked_results) - return result - + + return f"BM25 reranked results for '{query}':\n\n" + '\n\n'.join(reranked_results) + except Exception as e: print(f"ERROR: BM25 reranking failed: {e}") return f"Error: Reranking failed - {str(e)}" - diff --git a/tools_impl/search.py b/tools_impl/search.py deleted file mode 100644 index 1a7d552..0000000 --- a/tools_impl/search.py +++ /dev/null @@ -1,9 +0,0 @@ -from langchain.tools import BaseTool - -class SearchTool(BaseTool): - name: str = "web_search" - description: str = "Search the web for information" - - def _run(self, query: str) -> str: - # Simplified implementation for tutorial - return f"Search result for: {query}" \ No newline at end of file diff --git a/tools_impl/search_v2.py b/tools_impl/search_v2.py index 5e3edf6..f11d29e 100644 --- a/tools_impl/search_v2.py +++ b/tools_impl/search_v2.py @@ -1,10 +1,9 @@ from __future__ import annotations from typing import Any, Dict, List, Tuple, Optional -from pydantic import BaseModel, Field, field_validator +from pydantic import BaseModel from functools import lru_cache -# IMPORTANT: use langchain_core.tools for LC 0.2+ from langchain_core.tools import BaseTool from data.vector_store import VectorStore @@ -39,8 +38,7 @@ def _cached_search(query: str, top_k: int, min_score: float) -> List[Tuple[str, vs = _get_vector_store() # We ask store for a few extra and then threshold+trim, helps when many are < min_score raw = vs.search(query, top_k=min(top_k * 2, 50)) - # raw items expected as (doc_text, score, metadata) - filtered = [(d, s, m) for (d, s, m) in raw if isinstance(s, (int, float)) and s >= min_score] + filtered = [(d, s, m) for (d, s, m) in raw if s >= min_score] return filtered[:top_k] @@ -51,15 +49,7 @@ class SearchToolV2(BaseTool): description: str = "Semantic search using vector embeddings" args_schema: type[BaseModel] = SearchV2Input - # exclude heavy objects from Pydantic serialization - vector_store: Any = Field(default=None, exclude=True) - - def __init__(self, **data: Any): - super().__init__(**data) - # Lazy init; will raise a clean error on first use if uninitialized - self.vector_store = None - - def _run(self, query: str, top_k: int = 3, **kwargs) -> str: + def _run(self, query: str, top_k: int = 3, **kwargs: Any) -> str: try: # clamp for safety (in case someone bypasses args_schema) top_k = max(1, min(int(top_k), 20)) @@ -68,46 +58,19 @@ def _run(self, query: str, top_k: int = 3, **kwargs) -> str: results = _cached_search(query, top_k, min_score) if not results: - return ( - "No relevant documentation found for your query.\n\n" - f"```json\n{{\n" - f" \"query\": {query!r},\n" - f" \"top_k\": {top_k},\n" - f" \"min_score\": {min_score},\n" - f" \"count\": 0,\n" - f" \"items\": []\n" - f"}}\n```" - ) - - # Build concise human summary + machine-readable JSON + return "No relevant documentation found for your query." + + # Build concise human summary summary_lines = [f"πŸ“š Found {len(results)} relevant document(s):\n"] - items = [] - for idx, (doc, score, metadata) in enumerate(results, 1): - # brief snippet for readability - shortened to 200 chars + for idx, (doc, score, _metadata) in enumerate(results, 1): snippet = (doc or "").strip().replace("\n", " ") - if len(snippet) > 200: - snippet = snippet[:200] + "..." - - # Format more cleanly with number and indentation + if len(snippet) > 800: + snippet = snippet[:800] + "..." + summary_lines.append(f"{idx}. [Score: {score:.2f}]") summary_lines.append(f" {snippet}\n") - - items.append({ - "text": (doc or ""), - "score": float(score), - "metadata": metadata or {} - }) - - payload = { - "query": query, - "top_k": top_k, - "min_score": min_score, - "count": len(items), - "items": items - } - - # Return: clean human summary + compact JSON footer for tool chaining - return "\n".join(summary_lines) + f"\n---\n_Found {len(items)} results for: \"{query}\"_" + + return "\n".join(summary_lines) + f"\n---\n_Found {len(results)} results for: \"{query}\"_" except RuntimeError as e: # Embeddings not initialized, or explicit init errors diff --git a/tutorial_2.md b/tutorial_2.md index 8d96322..890244b 100644 --- a/tutorial_2.md +++ b/tutorial_2.md @@ -1,18 +1,6 @@ -# Smart AI Agent Targeting with MCP Tools +# Target LangGraph agents and MCP tools with LaunchDarkly AI configs -> Read the published version on [LaunchDarkly Docs](https://launchdarkly.com/docs/tutorials/multi-agent-mcp-targeting). _Published September 22nd, 2025 by Scarlett Attensil._ - - - -This tutorial was published in September 2025, before LaunchDarkly shipped several features that complement or supersede the targeting patterns shown below. The walkthrough still works, but for new builds you'll likely want to use: - -- [**Agent graphs**](https://launchdarkly.com/docs/home/ai-configs/agent-graphs) β€” externalize the multi-agent topology into a visual graph and combine it with the targeting rules in this tutorial -- [**Online evaluations**](https://launchdarkly.com/docs/home/ai-configs/online-evaluations) and [**custom judges**](https://launchdarkly.com/docs/home/ai-configs/custom-judges) β€” score live traffic per variation, including per-segment quality scores -- [**Prompt snippets**](https://launchdarkly.com/docs/home/ai-configs/snippets) β€” reusable prompt fragments so you can compose region-specific or tier-specific instructions without duplicating - -LaunchDarkly is also rebranding **AI Configs** as **AgentControl**. Slugs, SDK names, and APIs are unchanged. For the current reference, see [AgentControl documentation](https://launchdarkly.com/docs/home/ai-configs). - - +> Read the published version on [LaunchDarkly Docs](https://launchdarkly.com/docs/tutorials/multi-agent-mcp-targeting?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_multi-agent-mcp-targeting). _By Scarlett Attensil Β· Updated November 2026._ ## Overview @@ -20,28 +8,33 @@ Here's what nobody tells you about multi-agentic systems: the hard part isn't bu *Part 2 of 3 of the series: **Chaos to Clarity: Defensible AI Systems That Deliver on Your Goals*** -The solution? **LangGraph multi-agent workflows** controlled by **LaunchDarkly AI Config** targeting rules that intelligently route users: paid customers get premium tools and models, free users get cost-efficient alternatives, and EU users get Mistral for enhanced privacy. Use the **LaunchDarkly REST API** to set up a custom variant-targeting matrix in 2 minutes instead of spending hours setting it up manually. +The solution? **LangGraph multi-agent workflows** controlled by **LaunchDarkly Agent management** targeting rules that intelligently route users: paid customers get premium tools and models, free users get cost-efficient alternatives, and EU users get Mistral for enhanced privacy. Use the **LaunchDarkly REST API** to set up a custom variant-targeting matrix in 2 minutes instead of spending hours setting it up manually. ## What You'll Build Today In the next 18 minutes, you'll transform your basic multi-agent system with: -- **Business Tiers & MCP Integration**: Free users get internal keyword search, Paid users get premium models with RAG, external research tools and expanded tool call limits, all controlled by [LaunchDarkly AI Configs](https://launchdarkly.com/docs/home/ai-configs) +- **Business Tiers & MCP Integration**: Free users get internal keyword search, Paid users get premium models with RAG, external research tools and expanded tool call limits, all controlled by [LaunchDarkly Agent management](https://launchdarkly.com/docs/home/agentcontrol?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_multi-agent-mcp-targeting) - **Geographic Targeting**: EU users automatically get Mistral and Claude models (enhanced privacy), other users get cost-optimized alternatives -- **Smart Configuration**: Set up complex targeting matrices with [LaunchDarkly segments](https://launchdarkly.com/docs/home/flags/segments) and [targeting rules](https://launchdarkly.com/docs/home/flags/target) +- **Smart Configuration**: Set up complex targeting matrices with [LaunchDarkly segments](https://launchdarkly.com/docs/home/flags/segments?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_multi-agent-mcp-targeting) and [targeting rules](https://launchdarkly.com/docs/home/flags/target?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_multi-agent-mcp-targeting) ## Prerequisites βœ… **[Part 1 completed](README.md)** with exact naming: - Project: `multi-agent-chatbot` -- AI Configs: `supervisor-agent`, `security-agent`, `support-agent` +- AI configs: `supervisor-agent`, `security-agent`, `support-agent` - Tools: `search_v2`, `reranking` - Variations: `supervisor-basic`, `pii-detector`, `rag-search-enhanced` +πŸ‘€ **Accounts & API keys for external providers and MCP**: +- **LaunchDarkly Writer API token** (`LD_API_KEY`, created below) +- **Mistral account & API key** (`MISTRAL_API_KEY` for EU privacy routing): [sign up for free at console.mistral.ai](https://console.mistral.ai/), verify your email and phone for the free Experiment tier, then open **API Keys** and create a key +- **OpenAlex account** (free, no API key to copy): [sign up at openalex.org/signup](https://openalex.org/signup) so you can authorize the OpenAlex MCP server in Step 1 (includes about 500 searches per day) + πŸ”‘ **Add to your `.env` file**: ```bash -LD_API_KEY=your-api-key # Get from LaunchDarkly settings -MISTRAL_API_KEY=your-key # Get from console.mistral.ai (free, requires phone + email validation) +LD_API_KEY=your-api-key # Get from LaunchDarkly settings below +MISTRAL_API_KEY=your-key # Get from https://console.mistral.ai/ ``` ### Getting Your LaunchDarkly API Key @@ -96,7 +89,7 @@ Finally, add the token to your environment: Your agents need more than just your internal documents. **Model Context Protocol (MCP)** connects AI assistants to live external data and they agents become orchestrators of your digital infrastructure, tapping into databases, communication tools, development platforms, and any system that matters to your business. MCP tools run as separate servers that your agents call when needed. -> The [MCP Registry](https://registry.modelcontextprotocol.io) serves as a community-driven directory for discovering available MCP servers - like an app store for MCP tools. For this tutorial, we'll use manual installation since our specific academic research servers (ArXiv and Semantic Scholar) aren't yet available in the registry. +> The [MCP Registry](https://registry.modelcontextprotocol.io) serves as a community-driven directory for discovering available MCP servers - like an app store for MCP tools. For this tutorial, we'll install ArXiv locally and connect to the hosted [OpenAlex MCP server](https://mcp.openalex.org). Install external research capabilities: @@ -104,19 +97,23 @@ Install external research capabilities: # Install ArXiv MCP server for academic paper search uv tool install arxiv-mcp-server -# Install Semantic Scholar MCP server for citation data -git clone https://github.com/JackKuo666/semanticscholar-MCP-Server.git +# Sign in to the OpenAlex MCP server for scholarly works and citations +uv run python tools_impl/openalex_auth.py ``` +The OpenAlex sign-in opens your browser: +1. If you do not already have an OpenAlex account, click **Sign up** at [openalex.org/signup](https://openalex.org/signup) (free, includes about 500 MCP searches a day) and verify your email. +2. Sign in and click **Authorize** when prompted. Your OAuth tokens are saved locally to `.openalex_tokens.json` (gitignored, owner-only) and refresh automatically. + **MCP Tools Added:** - **arxiv_search**: Live academic paper search (Paid users) -- **semantic_scholar**: Citation and research database (Paid users) +- **openalex_search**: Scholarly works with citation counts (Paid users) These tools integrate with your agents via LangGraph while LaunchDarkly controls which users get access to which tools. ## Step 2: Configure with API Automation (2 minutes) -Now we'll use programmatic API automation to configure the complete setup. The [LaunchDarkly REST API](https://launchdarkly.com/docs/guides/api/rest-api) lets you manage tools, segments, and [AI Configs](https://launchdarkly.com/docs/home/ai-configs) programmatically. Instead of manually creating dozens of variations in the UI, this **configuration automation** makes REST API calls to provision user segments, AI Config variations, targeting rules, and tools. These are the same resources you could create manually through the LaunchDarkly dashboard. Your actual chat application continues running unchanged. +Now we'll use programmatic API automation to configure the complete setup. The [LaunchDarkly REST API](https://launchdarkly.com/docs/guides/api/rest-api?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_multi-agent-mcp-targeting) lets you manage tools, segments, and [AI configs](https://launchdarkly.com/docs/home/agentcontrol?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_multi-agent-mcp-targeting) programmatically. Instead of manually creating dozens of variations in the UI, this **configuration automation** makes REST API calls to provision user segments, config variations, targeting rules, and tools. These are the same resources you could create manually through the LaunchDarkly dashboard. Your actual chat application continues running unchanged. Configure your complete targeting matrix with one command: @@ -126,10 +123,10 @@ uv run python create_configs.py ``` **What the script creates**: -- **3 new tools**: `search_v1` (basic search), `arxiv_search` and `semantic_scholar` (MCP research tools) -- **4 combined user segments** with [geographic and tier targeting rules](https://launchdarkly.com/docs/home/flags/segments) -- **Updated AI Configs**: `security-agent` with 2 new geographic variations -- **Complete [targeting rules](https://launchdarkly.com/docs/home/flags/target)** that route users to appropriate variations +- **3 new tools**: `search_v1` (basic search), `arxiv_search` and `openalex_search` (MCP research tools) +- **4 combined user segments** with [geographic and tier targeting rules](https://launchdarkly.com/docs/home/flags/segments?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_multi-agent-mcp-targeting) +- **Updated configs**: `security-agent` with 2 new geographic variations (`basic-security`, `strict-security`) and `support-agent` with 5 new variations, each with its own `max_tool_calls` +- **Complete [targeting rules](https://launchdarkly.com/docs/home/flags/target?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_multi-agent-mcp-targeting)** that route users to appropriate variations - **Intelligently reuses** existing resources: `supervisor-agent`, `search_v2`, and `reranking` tools from Part 1 ### Understanding the Bootstrap Script @@ -161,10 +158,12 @@ def create_segment(self, project_key, segment_data): ```python # The script maps your YAML model IDs to LaunchDarkly's internal keys model_config_key_map = { - "claude-sonnet-4-6": "Anthropic.claude-sonnet-4-6", - "claude-haiku-4-5-20251001": "Anthropic.claude-haiku-4-5-20251001", - "gpt-4o": "OpenAI.gpt-4o", - "gpt-4o-mini": "OpenAI.gpt-4o-mini-2024-07-18", + "claude-sonnet-5-5": "Anthropic.claude-sonnet-5-5", + "claude-haiku-5-5": "Anthropic.claude-haiku-5-5", + "claude-opus-5-5": "Anthropic.claude-opus-5-5", + "gpt-6.2-sol": "OpenAI.gpt-6.2-sol", + "gpt-6.1-terra": "OpenAI.gpt-6.1-terra", + "gpt-6-luna": "OpenAI.gpt-6-luna", "mistral-small-latest": "Mistral.mistral-small-latest" } ``` @@ -213,7 +212,7 @@ The script handles the complexity of LaunchDarkly's API while letting you define πŸ”§ Creating tools... βœ… Tool 'search_v1' created βœ… Tool 'arxiv_search' created - βœ… Tool 'semantic_scholar' created + βœ… Tool 'openalex_search' created πŸ€– Ensuring AI configs exist... βœ… AI Config 'supervisor-agent' exists @@ -221,34 +220,71 @@ The script handles the complexity of LaunchDarkly's API while letting you define βœ… AI Config 'support-agent' exists 🧩 Creating variations... + πŸ”§ Using modelConfigKey: Anthropic.claude-haiku-5-5 + βœ… Variation 'basic-security' created + πŸ”§ Using modelConfigKey: Mistral.mistral-small-latest βœ… Variation 'strict-security' created + πŸ”§ Using modelConfigKey: Anthropic.claude-haiku-5-5 βœ… Variation 'eu-free' created + πŸ”§ Using modelConfigKey: Anthropic.claude-sonnet-5-5 βœ… Variation 'eu-paid' created + πŸ”§ Using modelConfigKey: OpenAI.gpt-6-luna βœ… Variation 'other-free' created + πŸ”§ Using modelConfigKey: OpenAI.gpt-6.2-sol βœ… Variation 'other-paid' created + πŸ”§ Using modelConfigKey: Anthropic.claude-haiku-5-5 + βœ… Variation 'international-standard' created πŸ“¦ Creating segments (for targeting rules)... βœ… Empty segment 'eu-free' created + πŸ”§ Adding 1 rules to segment 'eu-free' βœ… Rules added to segment 'eu-free' (final count: 1) βœ… Empty segment 'eu-paid' created + πŸ”§ Adding 1 rules to segment 'eu-paid' βœ… Rules added to segment 'eu-paid' (final count: 1) βœ… Empty segment 'other-free' created + πŸ”§ Adding 1 rules to segment 'other-free' βœ… Rules added to segment 'other-free' (final count: 1) βœ… Empty segment 'other-paid' created + πŸ”§ Adding 1 rules to segment 'other-paid' βœ… Rules added to segment 'other-paid' (final count: 1) 🎯 Updating targeting rules... + ⏭️ Skipping targeting for 'supervisor-agent' (empty rules) +πŸ“Š Available targeting variations for 'security-agent': ['pii-detector', 'basic-security', 'strict-security'] + βœ… Added rule: segment 'eu-free' -> variation 'strict-security' + βœ… Added rule: segment 'eu-paid' -> variation 'strict-security' + βœ… Added rule: segment 'other-free' -> variation 'basic-security' + βœ… Added rule: segment 'other-paid' -> variation 'basic-security' + βœ… Set fallthrough to variation 'basic-security' βœ… Targeting rules updated for 'security-agent' +πŸ“Š Available targeting variations for 'support-agent': ['rag-search-enhanced', 'eu-free', 'eu-paid', 'other-free', 'other-paid', 'international-standard'] + βœ… Added rule: segment 'eu-free' -> variation 'eu-free' + βœ… Added rule: segment 'eu-paid' -> variation 'eu-paid' + βœ… Added rule: segment 'other-free' -> variation 'other-free' + βœ… Added rule: segment 'other-paid' -> variation 'other-paid' + βœ… Set fallthrough to variation 'international-standard' βœ… Targeting rules updated for 'support-agent' ✨ Bootstrap complete! + +🎯 Next steps: + 1. Check your LaunchDarkly dashboard to verify configurations + 2. Test different user contexts with the demo + 3. Monitor usage patterns and adjust targeting rules + +πŸ”„ IMPORTANT REMINDER: + β€’ Future changes: Use LaunchDarkly UI only + β€’ Instructions: Modify in LaunchDarkly, not YAML + β€’ Targeting: Update in LaunchDarkly dashboard + β€’ This YAML file is now a historical record ``` **In your LaunchDarkly dashboard**, navigate to your `multi-agent-chatbot` project. You should see: -1. **AI Configs tab**: Three configs (`supervisor-agent`, `security-agent`, `support-agent`) with new variations -2. **Segments tab**: Four new segments (`eu-free`, `eu-paid`, `other-free`, `other-paid`) -3. **Tools tab**: Five tools total (including `search_v1`, `arxiv_search`, `semantic_scholar`) +1. **Agents > Configs**: Three configs (`supervisor-agent`, `security-agent`, `support-agent`) with new variations +2. **Segments**: Four new segments (`eu-free`, `eu-paid`, `other-free`, `other-paid`) +3. **Agents > Library > Tools**: Five tools total (including `search_v1`, `arxiv_search`, `openalex_search`) **Troubleshooting Common Issues**: @@ -281,7 +317,7 @@ Here's how the smart segmentation works: **By Business Tier:** - **Free users**: Basic search tools (`search_v1`) -- **Paid users**: Full research capabilities (`search_v1`, `search_v2`, `reranking`, `arxiv_search`, `semantic_scholar`) +- **Paid users**: Full research capabilities (`search_v1`, `search_v2`, `reranking`, `arxiv_search`, `openalex_search`) > **Note β€” AWS Bedrock inference region:** This geo-segmentation is fully correct for the **non-Bedrock** path (direct OpenAI / Anthropic / Mistral APIs) β€” EU vs non-EU routing of model, provider, and PII-redaction strictness works exactly as described. On the **AWS Bedrock** path it likewise segments the model and redaction correctly, but it **cannot segment the AWS inference region**: the region prefix is process-global (set once via `BEDROCK_INFERENCE_REGION`), so every Bedrock call in a deployment uses the same region regardless of the user's EU/non-EU segment. Making the inference region a per-variation property is a planned LaunchDarkly enhancement; until then, run separate deployments per region if EU-region inference is a hard requirement. @@ -311,27 +347,75 @@ Testing Geographic + Business Tier Targeting Matrix πŸ§ͺ TESTING: DE paid user (ID: user_eu_paid_001) ============================================================ πŸ“Š SUPPORT AGENT: - Model: claude-sonnet-4-6 (expected: claude-sonnet-4-6) βœ… + Model: claude-sonnet-5-5 (expected: claude-sonnet-5-5) βœ… Variation: eu-paid (expected: eu-paid) βœ… - Tools: ['search_v1', 'search_v2', 'reranking', 'arxiv_search', 'semantic_scholar'] βœ… - Expected: ['search_v1', 'search_v2', 'reranking', 'arxiv_search', 'semantic_scholar'] + Tools: ['search_v1', 'search_v2', 'reranking', 'arxiv_search', 'openalex_search'] βœ… + Expected: ['search_v1', 'search_v2', 'reranking', 'arxiv_search', 'openalex_search'] MCP Tools: Yes (should be: Yes) βœ… πŸ“ RESPONSE: - Length: 847 chars - Tools Called: ['search_v2', 'arxiv_search'] - Preview: Based on your request, I'll search both internal documentation and recent academic research... + Length: 697 chars + Tools Called: [] + Preview: Your message came through as "[Message withheld: the security check failed]", so I didn't receive yo... 🎯 RESULT: βœ… PASSED πŸ”„ Running: EU Free β†’ Claude Haiku + Basic Tools -[Similar detailed output for EU Free user...] -πŸ”„ Running: US Paid β†’ GPT-4 + Full MCP Tools -[Similar detailed output for US Paid user...] +============================================================ +πŸ§ͺ TESTING: DE free user (ID: user_eu_free_001) +============================================================ +πŸ“Š SUPPORT AGENT: + Model: claude-haiku-5-5 (expected: claude-haiku-5-5) βœ… + Variation: eu-free (expected: eu-free) βœ… + Tools: ['search_v1'] βœ… + Expected: ['search_v1'] + MCP Tools: No (should be: No) βœ… -πŸ”„ Running: US Free β†’ GPT-4o Mini + Basic Tools -[Similar detailed output for US Free user...] +πŸ“ RESPONSE: + Length: 258 chars + Tools Called: [] + Preview: I didn't receive your message. It was withheld because a security check failed, so I can't see what ... + +🎯 RESULT: βœ… PASSED + +πŸ”„ Running: US Paid β†’ GPT-6.2 Sol + Full MCP Tools + +============================================================ +πŸ§ͺ TESTING: US paid user (ID: user_other_paid_001) +============================================================ +πŸ“Š SUPPORT AGENT: + Model: gpt-6.2-sol (expected: gpt-6.2-sol) βœ… + Variation: other-paid (expected: other-paid) βœ… + Tools: ['search_v1', 'search_v2', 'reranking', 'arxiv_search', 'openalex_search'] βœ… + Expected: ['search_v1', 'search_v2', 'reranking', 'arxiv_search', 'openalex_search'] + MCP Tools: Yes (should be: Yes) βœ… + +πŸ“ RESPONSE: + Length: 374 chars + Tools Called: [] + Preview: What question or decision should the documentation research help you answer? Share the topic, any re... + +🎯 RESULT: βœ… PASSED + +πŸ”„ Running: US Free β†’ GPT-6 Luna + Basic Tools + +============================================================ +πŸ§ͺ TESTING: US free user (ID: user_other_free_001) +============================================================ +πŸ“Š SUPPORT AGENT: + Model: gpt-6-luna (expected: gpt-6-luna) βœ… + Variation: other-free (expected: other-free) βœ… + Tools: ['search_v1'] βœ… + Expected: ['search_v1'] + MCP Tools: No (should be: No) βœ… + +πŸ“ RESPONSE: + Length: 78 chars + Tools Called: [] + Preview: Of course. What documentation topic or question would you like me to research?... + +🎯 RESULT: βœ… PASSED ====================================================================== πŸ“Š FINAL RESULTS @@ -351,6 +435,8 @@ Testing Geographic + Business Tier Targeting Matrix This confirms your targeting matrix is working correctly across all user segments! +The test checks routing, not answers. Its query contains PII, so it goes through the security agent first. If Mistral's free tier rate limits the EU security agent (look for `SECURITY ERROR: ... 429` in the server logs), the security check fails closed: the support agent receives `[Message withheld: the security check failed]` instead of your message, as in the EU previews above, and the test still passes. + ## Step 5: Experience Segmentation in the Chat UI (3 minutes) Now let's see your segmentation in action through the user interface. With your backend already running from Step 4, start the UI: @@ -362,10 +448,10 @@ uv run streamlit run ui/chat_interface.py --server.port 8501 Open http://localhost:8501 and test different user types: -1. **User Dropdown**: Find the user dropdown by using the **>> icon** to open the **left nav menu**.. Select different regions (eu, other) and plans (Free, Paid). -2. **Ask Questions**: Try "Search for machine learning papers." -3. **Watch Workflow**: In the server logs, watch which model and tools get used for each user type. -4. **Verify Routing**: EU users get Mistral for security. Other users get GPT. Paid users get MCP tools. +1. **User Dropdown**: In the **Context** left sidebar, switch **User ID** between regions (`eu`, `other`) and plans (`free`, `paid`). +2. **Ask Questions**: Click **OpenAlex Research** or ask "Search for machine learning papers." +3. **Inspect Traces**: Click **`β†— View Trace Waterfall`** below any response (or watch the server logs) to inspect which variation, model, and tools ran for that user. +4. **Verify Routing**: EU users get Mistral for security. Other users get Claude Haiku for security and GPT for support. Paid users get MCP tools. ![Chat Interface User Selection](screenshots/chat_interface.png) @@ -395,11 +481,12 @@ This approach scales beyond tutorials. Whether you're serving 100 users or 100,0 ## Related tutorials -- [Build a LangGraph Multi-Agent system in 20 Minutes](https://launchdarkly.com/docs/tutorials/agents-langgraph) - Part 1: the multi-agent system this tutorial layers targeting on top of -- [Proving ROI with data-driven AI agent experiments](https://launchdarkly.com/docs/guides/experimentation/ai-experiments-roi) - Part 3: A/B test the targeted variations you just built -- [Beyond n8n for Workflow Automation: Agent Graphs](https://launchdarkly.com/docs/tutorials/agent-graphs) - Combine targeting with visual graph topology and per-node monitoring -- [Build AI Configs with Agent Skills](https://launchdarkly.com/docs/tutorials/agent-skills-quickstart) - Generate the agent and targeting configurations from natural-language prompts -- [Offline Evaluation of RAG-Grounded Answers](https://launchdarkly.com/docs/tutorials/offline-evals) - Validate each targeted variation against a reference dataset before rollout +- [Build a LangGraph multi-agent system in 20 minutes with LaunchDarkly AI configs](https://launchdarkly.com/docs/tutorials/agents-langgraph?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_multi-agent-mcp-targeting) - Part 1: the multi-agent system this tutorial layers targeting on top of +- [Prove LangGraph agent ROI with LaunchDarkly A/B experiments](https://launchdarkly.com/docs/guides/experimentation/ai-experiments-roi?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_multi-agent-mcp-targeting) - Part 3: A/B test the targeted variations you just built +- [Use LaunchDarkly Agent Skills in Claude Code and Cursor](https://launchdarkly.com/docs/tutorials/agent-skills-quickstart?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_multi-agent-mcp-targeting) - Generate the agent and targeting configurations from natural-language prompts +- [Benchmark LangGraph, Strands, OpenAI Agents, and Google ADK on the same agent graph](https://launchdarkly.com/docs/tutorials/agent-graph-experiments?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_multi-agent-mcp-targeting) - Compare four orchestrators on latency and token usage over one LaunchDarkly agent graph +- [Beyond n8n for workflow automation: agent graphs as your universal agent harness](https://launchdarkly.com/docs/tutorials/agent-graphs?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_multi-agent-mcp-targeting) - Combine targeting with visual graph topology and per-node monitoring +- [Evaluate RAG agent answers offline with LLM-as-a-judge in LaunchDarkly](https://launchdarkly.com/docs/tutorials/offline-evals?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_multi-agent-mcp-targeting) - Validate each targeted variation against a reference dataset before rollout --- -*Questions? Issues? Reach out at `aiproduct@launchdarkly.com` or open an issue in the [GitHub repo](https://github.com/launchdarkly-labs/devrel-agents-tutorial/tree/tutorial/agent-graphs).* +*Questions? Issues? Reach out at `aiproduct@launchdarkly.com` or open an issue in the [GitHub repo](https://github.com/launchdarkly-labs/devrel-agents-tutorial).* diff --git a/tutorial_3.md b/tutorial_3.md index 8f9d6fb..1e4dbb9 100644 --- a/tutorial_3.md +++ b/tutorial_3.md @@ -1,30 +1,17 @@ -# Proving ROI with data-driven AI agent experiments +# Prove LangGraph agent ROI with LaunchDarkly A/B experiments -> Read the published version on [LaunchDarkly Docs](https://launchdarkly.com/docs/guides/experimentation/ai-experiments-roi). +> Read the published version on [LaunchDarkly Docs](https://launchdarkly.com/docs/guides/experimentation/ai-experiments-roi?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi). _Updated November 2026._ ## Overview - - -This guide was published in October 2025, before LaunchDarkly shipped several features that supersede or extend the experiment patterns shown below. The methodology still works, but for new experiments you'll likely also want to use: - -- [**Online evaluations**](https://launchdarkly.com/docs/home/ai-configs/online-evaluations) and [**custom judges**](https://launchdarkly.com/docs/home/ai-configs/custom-judges) β€” LLM-as-a-judge scores feed directly into experiment metrics, so judge accuracy or toxicity can be the primary metric -- [**Agent graphs**](https://launchdarkly.com/docs/home/ai-configs/agent-graphs) β€” A/B test routing topology and per-node model choices, not just whole-config swaps -- [**Offline evaluations + datasets**](https://launchdarkly.com/docs/home/ai-configs/offline-evaluations) β€” lock in a regression baseline before running a live experiment -- [**LLM Playground**](https://launchdarkly.com/docs/home/ai-configs/playground) β€” pilot variations on test prompts before sending them to real traffic - -LaunchDarkly is also rebranding **AI Configs** as **AgentControl**. Slugs, SDK names, and APIs are unchanged. For the current reference, see [AgentControl documentation](https://launchdarkly.com/docs/home/ai-configs). - - - -This guide explains how to measure and prove the return on investment (ROI) of AI model changes with LaunchDarkly experiments. It shows you how to use statistical analysis to find unexpected performance wins and cost paradoxes. +This guide explains how to measure and prove the return on investment (ROI) of LangGraph multi-agent model and privacy changes with LaunchDarkly A/B experiments. It shows you how to use statistical analysis to find unexpected performance wins and cost paradoxes. Imagine a scenario where your CEO asks you "Is the new expensive AI model worth it? And does the enhanced privacy justify the cost?" By the end of this guide, you will be able to answer this question. You will run two A/B tests that reveal: - Whether aggressive PII redaction hurts user satisfaction -- Whether Claude Opus 4 is worth 33% more than GPT-4o +- Whether Claude Opus 5.5 is worth its premium over GPT-6.2 Sol - Any other unexpected gains from using the new model You can use this guide in one of two ways: @@ -37,14 +24,18 @@ You can use this guide in one of two ways: If you choose to complete the full tutorial, you need the following prerequisites: - An active LaunchDarkly project, set up according to the following tutorials: - - [Build a LangGraph Multi-Agent system in 20 Minutes with LaunchDarkly AI Configs](https://launchdarkly.com/docs/tutorials/agents-langgraph) - - [Smart AI Agent Targeting with MCP Tools](https://launchdarkly.com/docs/tutorials/multi-agent-mcp-targeting) -- API keys for Anthropic, OpenAI, and LaunchDarkly: - - [Sign up for a free LaunchDarkly account](http://app.launchdarkly.com/signup) and then [follow these instructions to get your API access token](https://launchdarkly.com/docs/home/account/api-create). + - [Build a LangGraph multi-agent system in 20 minutes with LaunchDarkly AI configs](https://launchdarkly.com/docs/tutorials/agents-langgraph?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) + - [Target LangGraph agents and MCP tools with LaunchDarkly AI configs](https://launchdarkly.com/docs/tutorials/multi-agent-mcp-targeting?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) +- Accounts and API keys configured in `.env` from Parts 1 and 2: + - **LaunchDarkly**: [sign up for a free LaunchDarkly account](https://app.launchdarkly.com/signup?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) and [create a Writer API access token](https://launchdarkly.com/docs/home/account/api-create?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) (`LD_SDK_KEY` and `LD_API_KEY`) + - **OpenAI**: [create an API key at platform.openai.com/api-keys](https://platform.openai.com/api-keys) (`OPENAI_API_KEY`) + - **Anthropic**: [create an API key at console.anthropic.com/settings/keys](https://console.anthropic.com/settings/keys) (`ANTHROPIC_API_KEY`) + - **Mistral**: [create a free API key at console.mistral.ai](https://console.mistral.ai/) (`MISTRAL_API_KEY`, used by the `Strict Security` treatment) + - **OpenAlex MCP**: signed in via `uv run python tools_impl/openalex_auth.py` ([free account at openalex.org/signup](https://openalex.org/signup)) ### Agent costs -The agent costs associated with the experiment may cost anywhere from \$5 to \$35. The default walk-through uses Claude Opus 4 (premium model) for testing. To reduce costs while still learning the experimentation patterns, you can modify `bootstrap/tutorial_3_experiment_variations.py` in your cloned repository to test with the free Mistral model instead. +The agent costs associated with the experiment may cost anywhere from \$5 to \$35. The default walk-through uses Claude Opus 5.5 (premium model) for testing. To reduce costs while still learning the experimentation patterns, you can modify `bootstrap/tutorial_3_experiment_variations.py` in your cloned repository to test with the free Mistral model instead. To reduce costs, change the following in the `create_premium_model_variations` function: @@ -54,21 +45,21 @@ To reduce costs, change the following in the `create_premium_model_variations` f ```python # Original (expensive): "model": { - "name": "claude-opus-4-7", - "provider": "anthropic" + "name": "claude-opus-5-5", + "provider": "Anthropic" } # Change to (free Mistral): "model": { "name": "mistral-small-latest", - "provider": "mistral" + "provider": "Mistral" } ``` -This reduces the experiment cost by about \$20. You will still have costs from the control group using GPT-4o and other agents in the system. +This reduces the experiment cost by about \$20. You will still have costs from the control group using GPT-6.2 Sol and other agents in the system. ## How the experiments work @@ -102,7 +93,7 @@ Here is an overview of the first experiment: - Hypothesis: "Strict security using free Mistral model with aggressive PII redaction will improve performance without harming user experience or significantly increasing system costs." - Variations (50% each): - - **Control**: Basic security with Claude Haiku, including moderate PII redaction + - **Control**: Basic security with Claude Haiku 5.5, including moderate PII redaction - **Treatment**: Strict security with Mistral free, including aggressive PII redaction - Success criteria: - Positive feedback rate: stable or improving (not significantly worse) @@ -114,19 +105,19 @@ Here is an overview of the first experiment: Here is an overview of the second experiment: -- Hypothesis: "Claude Opus 4 will justify its premium cost over GPT-4o due to its improved feedback rate." +- Hypothesis: "Claude Opus 5.5 will justify its premium cost over GPT-6.2 Sol due to its improved feedback rate." - Variations (50% each): - - **Control**: GPT-4o with full tools (current version) - - **Treatment**: Claude Opus 4 with identical tools + - **Control**: GPT-6.2 Sol with full tools (current version) + - **Treatment**: Claude Opus 5.5 with identical tools - Success criteria (must meet 90% threshold): - - β‰₯15% positive feedback rate improvement by Claude Opus 4 + - β‰₯15% positive feedback rate improvement by Claude Opus 5.5 - Cost-value ratio β‰₯ 0.25 (positive feedback rate gain % Γ· cost increase %) ## Step 1: Set up metrics This section explains how to configure the metrics needed for your two experiments. -Navigate to **Metrics** in LaunchDarkly and [create three custom metrics](https://launchdarkly.com/docs/home/metrics/create-metrics): +Navigate to **Metrics** in LaunchDarkly and [create three custom metrics](https://launchdarkly.com/docs/home/metrics/create-metrics?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi): @@ -205,7 +196,7 @@ Here is the detailed setup for the cost per request metric: -In addition to the above custom metrics, you will also use these [built-in metrics](https://launchdarkly.com/docs/home/metrics/autogen/ai): +In addition to the above custom metrics, you will also use these [built-in metrics](https://launchdarkly.com/docs/home/metrics/autogen/ai?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi):
@@ -230,7 +221,7 @@ In addition to the above custom metrics, you will also use these [built-in metri
-The cost tracking is implemented in `utils/cost_calculator.py`, which calculates actual dollar costs using the formula `(input_tokens Γ— input_price + output_tokens Γ— output_price) / 1M`. The system has pre-configured pricing for each model as of October 2025: GPT-4o at \$2.50/\$10 per million tokens, Claude Opus 4 at \$15/\$75, and Claude Sonnet at \$3/\$15. When a request completes, the cost is immediately calculated and sent to LaunchDarkly as a custom event, enabling direct cost-per-user analysis in your experiments. +The cost tracking is implemented in `utils/cost_calculator.py`, which calculates actual dollar costs using the formula `(input_tokens Γ— input_price + output_tokens Γ— output_price) / 1M`. The system has pre-configured pricing for each model from the LaunchDarkly model catalog: GPT-6.2 Sol at \$2/\$10 per million tokens, Claude Opus 5.5 at \$4/\$20, and Claude Haiku 5.5 at \$0.10/\$0.50. When a request completes, the cost is immediately calculated and sent to LaunchDarkly as a custom event, enabling direct cost-per-user analysis in your experiments. ## Step 2: Create experiment variations @@ -246,11 +237,11 @@ uv run python bootstrap/tutorial_3_experiment_variations.py -This creates the `claude-opus-treatment` variation for the "Premium model value analysis" experiment. To verify the script worked correctly, navigate to your "support-model-config" feature flag in LaunchDarkly. You should now see the `claude-opus-treatment` variation alongside your existing variations. The "Security agent analysis" experiment will use your existing baseline and enhanced variations. Both experiments use the existing `other-paid` configuration as their control group. +This creates the `claude-opus-treatment` variation for the "Premium model value analysis" experiment. To verify the script worked correctly, open your `support-agent` config in LaunchDarkly. You should now see the `claude-opus-treatment` variation alongside your existing variations. The "Security agent analysis" experiment will use your existing `basic-security` and `strict-security` variations. Both experiments use the existing `other-paid` configuration as their control group. ## Step 3: Configure the security agent experiment -In the left navigation, expand **AI**, then select **Configs**, then open **security-agent**. In the right navigation, click the plus **+** sign next to **Experiments** to create a new experiment. +In the left navigation, expand **Agents**, then select **Configs**, then open **security-agent**. In the right navigation, click the plus **+** sign next to **Experiments** to create a new experiment. Here is how to set up your experiment: @@ -262,7 +253,7 @@ Here is how to set up your experiment: - `Negative feedback rate` - `p95_total_user_latency` - `ai_cost_per_request` -- **Flag or AI Config**: security-agent +- **Flag or AI config**: security-agent **Targeting rule:** Rule 4 - This configures `If Context` > `is in Segment` then `Other Paid` - **Variations served outside of this experiment:** `Basic Security` @@ -286,12 +277,12 @@ You may see a "Health warning" indicator after starting the experiment. This is ## Step 4: Configure the premium model experiment -In the left navigation, expand **AI**, then select **Configs**, then open **support-agent**. In the right navigation, click the plus **+** sign next to **Experiments** to create a new experiment. +In the left navigation, expand **Agents**, then select **Configs**, then open **support-agent**. In the right navigation, click the plus **+** sign next to **Experiments** to create a new experiment. Here is how to set up your experiment: - **Name:** Premium model value analysis -- **Hypothesis:** "Claude Opus 4 will justify its premium cost over GPT-4o due to its improved feedback rate." +- **Hypothesis:** "Claude Opus 5.5 will justify its premium cost over GPT-6.2 Sol due to its improved feedback rate." - **Randomize by:** `user` - **Metrics:** Click "Select metrics or metric groups" and add: - `Positive feedback rate`: Select first to set as **Primary** @@ -299,7 +290,7 @@ Here is how to set up your experiment: - `p95_total_user_latency` - `average_total_user_tokens` - `ai_cost_per_request` -- **Flag or AI Config**: support-agent +- **Flag or AI config**: support-agent - **Targeting rule:** Rule 4 - This configures `If Context` > `is in Segment` then `Other Paid` - **Variations served outside of this experiment:** `other-paid` @@ -312,7 +303,7 @@ Here is how to set up your experiment: - `other-paid`: `50%` - `international-standard`: `0%` - `claude-opus-treatment`: `50%` - - To set these percentages, first scroll down to the **Control** field and set `Basic Security` as the control variation, otherwise you won't be able to allocate 50% traffic to it. + - To set these percentages, first scroll down to the **Control** field and set `other-paid` as the control variation, otherwise you won't be able to allocate 50% traffic to it. - **Control:** `other-paid` - **Statistical approach:** `Bayesian` - **Threshold:** `90%` @@ -330,7 +321,7 @@ You may see a "Health warning" indicator after starting the experiment. This is If two independent experiments are running concurrently on the same users, then each user experiences: - One security variation (`Basic Security` or `Strict Security`) -- One model variation (`Claude Opus 4 Treatment` or `Other Paid (GPT-4o)`) +- One model variation (`Claude Opus 5.5 Treatment` or `Other Paid`) Random assignment ensures balance, because ~50% of users receive each combination. @@ -360,8 +351,9 @@ uv run python -u tools/concurrent_traffic_generator.py --queries 200 --concurren This configuration includes: -- 200 queries by default. You can edit the script to change this number. +- 200 queries, set by `--queries` (the default is 50). - 10 concurrent requests running in parallel. +- 15% of queries with PII by default, set by `--pii-percentage`. - 2000-second timeout (33 minutes) per request to handle MCP tool rate limits. Runtime depends largely on if you retain MCP tool enablement as these take much longer to complete. @@ -386,35 +378,52 @@ uv run python tools/traffic_generator.py --queries 50 --delay 2 What happens during traffic simulation: -1. **Knowledge extraction:** Claude analyzes your docs and identifies 20+ realistic topics +1. **Topic generation:** Claude lists reinforcement learning topics from the sample Sutton & Barto textbook in `kb/` (20 for the concurrent generator, 15 for the sequential one) 2. **Query generation:** Each test randomly selects from these topics for diversity -3. **AI-powered evaluation:** Claude judges responses as thumbs_up/thumbs_down/neutral +3. **AI-powered evaluation:** Claude judges each response as `positive` (thumbs up), `negative` (thumbs down), or `none` (no rating), and the generator sends positive and negative feedback to the API 4. **Automatic tracking:** All metrics flow to LaunchDarkly in real-time -Here is an example of the traffic generation output you might see: +Here is the output of a short run with `--queries 10 --concurrency 5`. A 200-query run prints the same lines, one per query: ``` -πŸ“š Analyzing knowledge base... -βœ… Generated 23 topics - -⚑ Sending 200 requests with 10 concurrent workers... +πŸš€ Concurrent Traffic Generator +====================================================================== +Queries: 10 +Concurrency: 5 parallel requests +Timeout: 2000s (33 minutes) per request +Target: http://localhost:8000 +====================================================================== -βœ… [1/200] Success (23.4s) - other_paid: What is reinforcement learning?... -βœ… [2/200] Success (45.2s) - other_paid: How does Q-learning work?... -⏱️ [15/200] Timeout (>2000s) - other_paid: Complex research query... - ↑ This is normal - MCP rate limits -βœ… [200/200] Success (387.1s) - other_paid: Explain temporal difference... +πŸ“š Generating base topics... +βœ… Generated 20 base topics +πŸ”„ Generating 10 queries concurrently (15% with PII)... +πŸ“ Generated 10/10 queries... +βœ… Generated 10 queries concurrently (2 with PII, 8 clean) + +⚑ Sending 10 requests with 5 concurrent workers... + +βœ… [1/10] Success (13.3s) - other_paid: Hi, I'm Dana Whitfield, a Senior ML Engineer at Brightpath A... +βœ… [2/10] Success (18.8s) - other_paid: What's the basic idea behind dynamic programming in reinforc... +βœ… [3/10] Success (24.6s) - other_paid: How does SARSA differ from Q-learning in terms of how they u... +βœ… [4/10] Success (27.3s) - other_paid: How does value iteration's convergence guarantee depend on t... +βœ… [5/10] Success (18.0s) - other_paid: How do Monte Carlo methods differ from temporal difference l... +βœ… [6/10] Success (10.4s) - other_paid: What's the basic idea behind dynamic programming in reinforc... +βœ… [7/10] Success (37.9s) - other_paid: How does the Dyna-Q algorithm's use of simulated experience ... +βœ… [8/10] Success (22.9s) - other_paid: How does on-policy prediction with function approximation di... +βœ… [9/10] Success (15.6s) - other_paid: Hi, I'm Sarah Johnson, a Product Manager at Brightwave Analy... +βœ… [10/10] Success (32.4s) - other_paid: How does SARSA's on-policy update interact with function app... ====================================================================== βœ… COMPLETE ====================================================================== -Total time: 45.3 minutes (2718s) -Successful: 195/200 (97.5%) -Failed: 5/200 (2.5%) -Average: 13.6s per query (with concurrency) +Total time: 1.0 minutes (61s) +Successful: 10/10 (100.0%) +Failed: 0/10 (0.0%) +Average: 6.1s per query (with concurrency) +====================================================================== ``` @@ -423,7 +432,7 @@ Average: 13.6s per query (with concurrency) Relevant performance information includes: - Most queries complete in 10-60 seconds -- Queries using `semantic_scholar` MCP tool may take 5-20 minutes due to API rate limits +- Each `openalex_search` call spends part of your free OpenAlex daily budget of about 500 searches - Concurrent execution handles slow requests gracefully by continuing with others - Failed/timeout requests (typically less than 5%) don't affect experiment validity @@ -433,7 +442,7 @@ Refresh your LaunchDarkly experiment **Results** tabs to see data flowing in. Co ## Interpreting your results -After your experiments have collected data from about 100 users per variation, you'll see results in the LaunchDarkly UI. Here's how to interpret them: +After your experiments have collected data from about 100 users per variation, you'll see results in the LaunchDarkly UI. Here's how to interpret them. The results below come from our October 2025 run, which compared Claude Opus 4 with GPT-4o and used GPT-4o mini as the supervisor, so your numbers will differ: ### Question 1: Security agent analysis @@ -519,7 +528,7 @@ IF positive_feedback_rate increase β‰₯ 15% AND probability_to_beat for positive_feedback_rate β‰₯ 90% AND probability_to_beat for cost β‰₯ 90% AND cost-value ratio increase β‰₯ .25 -THEN deploy_claude_opus_4() +THEN deploy_claude_opus() ELSE keep_current_model() ``` @@ -539,7 +548,7 @@ Here's what we learned running these experiments ourselves: - Low-variance metrics (latency, tokens) reach significance quickly (~1,000 samples). High-variance metrics (cost, feedback) may need 5,000-10,000+ samples. This isn't a flaw in your experiment but the reality of statistical power. Don't chase 90% confidence on every metric; focus on directional insights for high-variance metrics and statistical proof for low-variance ones. -- Using a free Mistral model for security reduced that agent's cost to \$0, yet increased total system cost by 14.5 because downstream agents had to work harder with reduced context. However, the experiment also revealed an unexpected 36% latency improvement. Mistral is not just free but significantly faster. LaunchDarkly's user-level tracking captured both effects, enabling an informed decision: enhanced privacy + faster responses for ~\$0.004 more per request is a worthwhile tradeoff. +- Using a free Mistral model for security reduced that agent's cost to \$0, yet increased total system cost by 14.5% because downstream agents had to work harder with reduced context. However, the experiment also revealed an unexpected 36% latency improvement. Mistral is not just free but significantly faster. LaunchDarkly user-level tracking captured both effects, enabling an informed decision: enhanced privacy + faster responses for ~\$0.004 more per request is a worthwhile tradeoff. - At 87% confidence for latency (as compared to 90% target), the 36% improvement is clear enough for decision-making. Perfect statistical significance is ideal, but 85-89% confidence combined with other positive signals (stable feedback, acceptable cost) can justify deployment when the effect size is large. @@ -551,7 +560,7 @@ We encountered some limitations while running these experiments: - **Independent experiments:** While random assignment naturally balances security versions across model versions, preventing systematic bias, you cannot analyze interaction effects between security and model choices. If interaction effects are important to your use case, consider running a proper [factorial experiment design](https://en.wikipedia.org/wiki/Factorial_experiment). -- **Statistical confidence:** LaunchDarkly uses [Bayesian statistics](https://launchdarkly.com/docs/home/experimentation/bayesian) to calculate confidence, where 90% confidence means there's a 90% probability the true effect is positive. This is not the same as p-value < 0.10 from [frequentist tests](https://en.wikipedia.org/wiki/Frequentist_inference). We set the threshold at 90%, rather than 95%, to balance false positives versus false negatives, though for mission-critical features you should consider raising the confidence threshold to 95%. +- **Statistical confidence:** LaunchDarkly uses [Bayesian statistics](https://launchdarkly.com/docs/home/experimentation/bayesian?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) to calculate confidence, where 90% confidence means there's a 90% probability the true effect is positive. This is not the same as p-value < 0.10 from [frequentist tests](https://en.wikipedia.org/wiki/Frequentist_inference). We set the threshold at 90%, rather than 95%, to balance false positives versus false negatives, though for mission-critical features you should consider raising the confidence threshold to 95%. ## Common mistakes you have avoided @@ -597,11 +606,11 @@ This section includes troubleshooting solutions. ### **Long response times (>20 minutes)** -If you see requests taking exceptionally long, the root cause is likely the `semantic_scholar` MCP tool hitting API rate limits, which causes 30-second retry delays. Queries using this tool may take 5-20 minutes to complete. The 2000-second timeout handles this gracefully, but if you need faster responses (60-120 seconds typical), consider removing `semantic_scholar` from tool configurations. You can verify this issue by checking logs for `HTTP/1.1 429` errors indicating rate limiting. +If you see requests taking exceptionally long, check the server logs for `HTTP/1.1 429` errors, which mean an MCP research tool is being rate limited. A large experiment run can use up the free OpenAlex daily budget, after which `openalex_search` calls fail until the next day. The 2000-second timeout handles slow requests gracefully, but if you need faster responses (60-120 seconds typical), consider removing `openalex_search` and `arxiv_search` from tool configurations. ### **Cost metrics not appearing** -If `ai_cost_per_request` events aren't showing in LaunchDarkly, first verify that `utils/cost_calculator.py` has pricing configured for your models. Cost is only tracked when requests complete successfully (not on timeout or error). The system flushes cost events to LaunchDarkly immediately after each request completion. To debug, look for `COST CALCULATED:` and `COST TRACKING (async):` messages in your API logs. +If `ai_cost_per_request` events aren't showing in LaunchDarkly, first verify that `utils/cost_calculator.py` has pricing configured for your models. Cost is only tracked when requests complete successfully (not on timeout or error). The system flushes cost events to LaunchDarkly immediately after each request completion. To debug, look for `TOKENS:` and `COST CALCULATED:` messages in your API logs. ## Beyond this tutorial: Advanced AI Experimentation patterns @@ -610,11 +619,11 @@ In this guide you ran two experiments: - **Security‑agent test**: a bundle change, where both prompt/instructions and the model changed. - **Premium‑model test**: a model‑only change. -AI Configs come in two modes: **prompt‑based** (single‑step completions) and **agent‑based** (multi‑step workflows with tools). Below are additional patterns to explore. +AI configs come in two modes: **prompt‑based** (single‑step completions) and **agent‑based** (multi‑step workflows with tools). Below are additional patterns to explore. -### AI Config experiments +### AI config experiments -Experiments you can run entirely in AI Configs with no app redeploy include: +Experiments you can run entirely in AI configs with no app redeploy include: - **Prompt and template experiments (prompt‑based or agent instructions):** Duplicate a variation and iterate on system/assistant messages or agent instructions to measure adherence to schema, tone, or qualitative satisfaction. Use LaunchDarkly Experimentation to tie those variations to product metrics. @@ -633,7 +642,7 @@ Recommendations include: Experiments you can run with feature flags include: -- **Fine‑grained RAG tuning:** k‑values, similarity thresholds, chunking, reranker swaps, and cache policy are typically coded inside your retrieval layer. Expose these as flags or AI Config custom parameters if you want to A/B them. +- **Fine‑grained RAG tuning:** k‑values, similarity thresholds, chunking, reranker swaps, and cache policy are typically coded inside your retrieval layer. Expose these as flags or config custom parameters if you want to A/B them. - **Tool‑routing guardrails:** Fallback flows (for example, retry with a different tool/model on error), escalation rules, or heuristics need logic in your agent/orchestrator. Gate those behaviors behind flags and measure with custom metrics. @@ -645,30 +654,30 @@ Experiments you can run with feature flags include: These ideas work with all of the experiment suggestions we listed above: -- Target by plan/tier, geo, device, or org using AI Config targeting rules and percentage rollouts. +- Target by plan/tier, geo, device, or org using config targeting rules and percentage rollouts. - Keep variations narrow, one change per experiment, to avoid confounding. Reserve "bundle" tests for tool‑stack comparisons. -Require statistical evidence before shipping configuration changes. Pair each variation with clear success metrics, then A/B test prompt or tool adjustments and use confidence intervals to confirm improvements. When you introduce the new code paths above, protect them behind feature flags so you can run sequential tests, [multi-armed bandits](https://launchdarkly.com/docs/home/multi-armed-bandits) for faster convergence, or change your [experiment design](https://launchdarkly.com/docs/guides/experimentation/designing-experiments) to understand how prompts, tools, and safety levers interact. +Require statistical evidence before shipping configuration changes. Pair each variation with clear success metrics, then A/B test prompt or tool adjustments and use confidence intervals to confirm improvements. When you introduce the new code paths above, protect them behind feature flags so you can run sequential tests, [multi-armed bandits](https://launchdarkly.com/docs/home/multi-armed-bandits?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) for faster convergence, or change your [experiment design](https://launchdarkly.com/docs/guides/experimentation/designing-experiments?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) to understand how prompts, tools, and safety levers interact. ## Conclusion: From chaos to clarity -Across this three-part series, you've transformed from hardcoded AI configurations to a scientifically rigorous, data-driven optimization engine. [Part 1](https://launchdarkly.com/docs/tutorials/agents-langgraph) established your foundation with a dynamic multi-agent [LangGraph](https://langchain-ai.github.io/langgraph/) system controlled by [LaunchDarkly AI Configs](https://launchdarkly.com/docs/guides/ai-configs), eliminating the need for code deployments when adjusting AI behavior. [Part 2](https://launchdarkly.com/docs/tutorials/multi-agent-mcp-targeting) added sophisticated targeting with geographic privacy rules, user segmentation by plan tiers, and [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) tool integration for real academic research capabilities. This tutorial, Part 3, completed your journey with statistical experimentation that proves ROI and guides optimization decisions with mathematical confidence rather than intuition. +Across this three-part series, you've transformed from hardcoded AI configurations to a scientifically rigorous, data-driven optimization engine. [Part 1](https://launchdarkly.com/docs/tutorials/agents-langgraph?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) established your foundation with a dynamic multi-agent [LangGraph](https://langchain-ai.github.io/langgraph/) system controlled by [LaunchDarkly Agent management](https://launchdarkly.com/docs/home/agentcontrol?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi), eliminating the need for code deployments when adjusting AI behavior. [Part 2](https://launchdarkly.com/docs/tutorials/multi-agent-mcp-targeting?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) added sophisticated targeting with geographic privacy rules, user segmentation by plan tiers, and [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) tool integration for real academic research capabilities. This guide, Part 3, completed your journey with statistical experimentation that proves ROI and guides optimization decisions with mathematical confidence rather than intuition. You now possess a defensible AI system that adapts to changing requirements, scales across user segments, and continuously improves through measured experimentation. Your stakeholders receive concrete evidence for AI investments, your engineering team deploys features with statistical backing, and your users benefit from optimized experiences driven by real data rather than assumptions. The chaos of ad-hoc AI development has given way to clarity through systematic, scientific product development. -{version === "LaunchDarkly docs" && ( - -Your 14-day trial begins as soon as you sign up. Get started in minutes using the in-app Quickstart. You'll discover how easy it is to release, monitor, and optimize your software.

- -Want to try it out? Start a trial. - -
)} +> **Want to know more? Start a trial.** +> +> Your 14-day trial begins as soon as you sign up. Get started in minutes using the in-app Quickstart. You'll discover how easy it is to release, monitor, and optimize your software. +> +> Want to try it out? [Start a trial](https://app.launchdarkly.com/signup?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi). ## Related tutorials -- [Build a LangGraph Multi-Agent system in 20 Minutes](https://launchdarkly.com/docs/tutorials/agents-langgraph) - Part 1 of this series: build the agent system that the experiments here measure -- [Smart AI Agent Targeting with MCP Tools](https://launchdarkly.com/docs/tutorials/multi-agent-mcp-targeting) - Part 2: add user, geo, and tier targeting before experimenting on it -- [Beyond n8n for Workflow Automation: Agent Graphs](https://launchdarkly.com/docs/tutorials/agent-graphs) - Externalize the multi-agent topology with visual graph builder and per-node metrics -- [When to add online evals](https://launchdarkly.com/docs/tutorials/when-to-add-online-evals) - Surface the metrics experiments measure with judge-based scoring on live traffic -- [Offline Evaluation of RAG-Grounded Answers](https://launchdarkly.com/docs/tutorials/offline-evals) - Lock in an offline baseline before running A/B tests -- [Evaluate LLM code generation with LLM-as-judge evaluators](https://launchdarkly.com/docs/tutorials/custom-evals-claude-code) - Build custom judges to produce the quality metrics your experiments compare \ No newline at end of file +- [Build a LangGraph multi-agent system in 20 minutes with LaunchDarkly AI configs](https://launchdarkly.com/docs/tutorials/agents-langgraph?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) - Part 1 of this series: build the agent system that the experiments here measure +- [Target LangGraph agents and MCP tools with LaunchDarkly AI configs](https://launchdarkly.com/docs/tutorials/multi-agent-mcp-targeting?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) - Part 2: add user, geo, and tier targeting before experimenting on it +- [Benchmark LangGraph, Strands, OpenAI Agents, and Google ADK on the same agent graph](https://launchdarkly.com/docs/tutorials/agent-graph-experiments?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) - Compare four orchestrators on latency and token usage over one LaunchDarkly agent graph +- [Beyond n8n for workflow automation: agent graphs as your universal agent harness](https://launchdarkly.com/docs/tutorials/agent-graphs?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) - Externalize the multi-agent topology with visual graph builder and per-node metrics +- [Evaluate RAG agent answers offline with LLM-as-a-judge in LaunchDarkly](https://launchdarkly.com/docs/tutorials/offline-evals?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) - Lock in an offline baseline before running A/B tests +- [Run AgentControl offline evaluations in CI](https://launchdarkly.com/docs/tutorials/aic-cicd?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) - Gate prompt and retriever changes on pull requests before starting live experiments +- [Evaluate LLM code generation with LLM-as-judge evaluators](https://launchdarkly.com/docs/tutorials/custom-evals-claude-code?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) - Build custom judges to produce the quality metrics your experiments compare +- [When to add online evals](https://launchdarkly.com/docs/tutorials/when-to-add-online-evals?utm_source=github&utm_medium=referral&utm_campaign=devrel_fy27&utm_content=scarlett_ai-experiments-roi) - Surface the metrics experiments measure with judge-based scoring on live traffic \ No newline at end of file diff --git a/ui/assets/albert-proud.png b/ui/assets/albert-proud.png new file mode 100644 index 0000000..6a66bb3 Binary files /dev/null and b/ui/assets/albert-proud.png differ diff --git a/ui/assets/avatar-assistant.png b/ui/assets/avatar-assistant.png new file mode 100644 index 0000000..6627254 Binary files /dev/null and b/ui/assets/avatar-assistant.png differ diff --git a/ui/assets/avatar-user.png b/ui/assets/avatar-user.png new file mode 100644 index 0000000..4b9b534 Binary files /dev/null and b/ui/assets/avatar-user.png differ diff --git a/ui/assets/launchdarkly-logo-white.svg b/ui/assets/launchdarkly-logo-white.svg new file mode 100644 index 0000000..0e1379e --- /dev/null +++ b/ui/assets/launchdarkly-logo-white.svg @@ -0,0 +1,11 @@ + + + + + + + + + \ No newline at end of file diff --git a/ui/chat_interface.py b/ui/chat_interface.py index bdea5b7..a462b41 100644 --- a/ui/chat_interface.py +++ b/ui/chat_interface.py @@ -1,12 +1,37 @@ -import streamlit as st -import requests -import json +import base64 import os +from pathlib import Path +import requests +import streamlit as st from dotenv import load_dotenv # Load environment variables load_dotenv() +UI_DIR = Path(__file__).resolve().parent +ASSETS_DIR = UI_DIR / "assets" +KB_DIR = UI_DIR.parent / "kb" +ALBERT_AVATAR = ASSETS_DIR / "albert-proud.png" +USER_AVATAR = ASSETS_DIR / "avatar-user.png" +ASSISTANT_AVATAR = ASSETS_DIR / "avatar-assistant.png" +LD_WORDMARK_SVG = ASSETS_DIR / "launchdarkly-logo-white.svg" + +# Clear identifiers (always redacted) plus employer, city, and role (redacted only by strict security). +SECURITY_CHECK_QUERY = ( + "My name is Jane Doe, email jane.doe@example.com. " + "I work at Acme Corp in Berlin as a manager. " + "Can you explain temporal-difference learning?" +) + +LD_LOGO_B64 = base64.b64encode(LD_WORDMARK_SVG.read_bytes()).decode("ascii") +ALBERT_B64 = base64.b64encode(ALBERT_AVATAR.read_bytes()).decode("ascii") +KB_FILES = sorted(p.name for p in KB_DIR.glob("*.pdf")) +KB_SUMMARY = ( + f"{', '.join(KB_FILES)} (Reinforcement Learning)" + if KB_FILES == ["SuttonBartoIPRLBook2ndEd.pdf"] + else (", ".join(KB_FILES) if KB_FILES else "No PDFs in kb/") +) + # Sample users for LaunchDarkly targeting (hardcoded) sample_users = [ {"id": "user_other_free_001", "country": "US", "region": "other", "plan": "free"}, @@ -38,321 +63,357 @@ def get_user_context(user_id, sample_users): print(f" UI: User not found, using default context: {default_context}") return default_context -# Get API configuration from environment +# Get API and LaunchDarkly project configuration from environment API_HOST = os.getenv('API_HOST', 'localhost') API_PORT = os.getenv('API_PORT', '8000') API_BASE_URL = f"http://{API_HOST}:{API_PORT}" - -# Get UI configuration from environment -UI_PORT = int(os.getenv('UI_PORT', '8501')) +LD_PROJECT_KEY = os.getenv('LD_PROJECT_KEY', 'multi-agent-chatbot') +LD_APP_URL = os.getenv('LD_APP_URL', 'https://app.launchdarkly.com').rstrip('/') st.set_page_config( - page_title="LangGraph Multi-Agent System", - page_icon="β†’", + page_title="LaunchDarkly Multi-Agent System", + page_icon=str(ALBERT_AVATAR), layout="wide", - initial_sidebar_state="collapsed" + initial_sidebar_state="expanded" ) st.markdown(""" - - -""", unsafe_allow_html=True) - -# Simplified header section -st.markdown(""" -
-

LaunchDarkly Multi-Agent System

-

Intelligent document search and research powered by LangGraph and RAG architecture

-
""", unsafe_allow_html=True) -def process_tool_display(tools, tool_details): - """Single function to process tools and tool_details for consistent UI display""" - tool_list = [] - - # Handle None values - if tools is None: - tools = [] - if tool_details is None: - tool_details = [] - - # Define mapping from actual tool names to display names - mcp_name_mapping = { - "search_papers": "arxiv_search", - "search_semantic_scholar": "semantic_scholar" - } - - for i, tool in enumerate(tools): - tool_name = tool if isinstance(tool, str) else tool.get("name", str(tool)) - - # Get search query from matching tool_details with proper name mapping - # Use index-based matching for multiple instances of the same tool - search_query = "" - if i < len(tool_details): - detail = tool_details[i] - detail_name = detail.get("name") - # Check both direct match and mapped match - mapped_name = mcp_name_mapping.get(detail_name, detail_name) - if mapped_name == tool_name: - search_query = detail.get("search_query", "") or "" - - # Add tool with search query if available - if search_query: - tool_list.append(f"{tool_name} ('{search_query}')") - else: - tool_list.append(tool_name) - - return tool_list - -# Enhanced example queries section -st.markdown(""" -
-

Example Queries

-

Test different tool combinations with these curated queries

+st.markdown(f""" +
+
+
+ Research demo +

Multi-Agent Research System

+

A LangGraph supervisor, a PII security boundary, and hybrid RAG with live academic search.

+
+
+ Albert +
+
+
+ LaunchDarkly + {KB_SUMMARY} Β· ArXiv Β· OpenAlex +
""", unsafe_allow_html=True) -# Row 1: Basic search tools -col1, col2 = st.columns(2) -with col1: - if st.button("Basic Search", use_container_width=True): - st.session_state.example_query = "What are the key concepts I should understand from your knowledge base?" - -with col2: - if st.button("RAG + Reranking", use_container_width=True): - st.session_state.example_query = "Search for implementation guidance, then rerank the results to show me the most relevant information" - -# Row 2: Security and research tools -col4, col5, col6 = st.columns(3) -with col4: - if st.button("Security Check", use_container_width=True): - st.session_state.example_query = "My name is John Doe, email: john.doe@example.com. I'm a VP at StarSystems, and I need help with my account" - -with col5: - if st.button("ArXiv Research", use_container_width=True): - st.session_state.example_query = "Find recent ArXiv papers on machine learning from the last 6 months" - -with col6: - if st.button("Semantic Scholar", use_container_width=True): - st.session_state.example_query = "Search Semantic Scholar for research papers on artificial intelligence with citations" - -# Row 3: Advanced research -col7 = st.columns(1)[0] -with col7: - if st.button("Full Research Stack", use_container_width=True): - st.session_state.example_query = "Compare what you know from your internal documentation with recent academic research papers" +def show_observability_links(metadata): + """Render served summary, PII redaction confirmation, and direct LaunchDarkly Trace & Monitoring links.""" + import html + from urllib.parse import quote + + agent_configurations = metadata.get("agent_configurations") or [] + support = next((a for a in agent_configurations if a.get("agent_name") == "support-agent"), {}) + security = next((a for a in agent_configurations if a.get("agent_name") == "security-agent"), {}) + + variation = support.get("variation_key") or metadata.get("primary_variation", "unknown") + model = support.get("model") or metadata.get("primary_model", "unknown") + tools_used = support.get("tools_used") or metadata.get("tools_used") or [] + tools_summary = f" Β· tools: {', '.join(tools_used)}" if tools_used else "" + + trace_id = metadata.get("trace_id") + span_id = metadata.get("span_id") + trace_ts = metadata.get("trace_timestamp") + if trace_id and span_id and trace_ts: + import json as _json + related = base64.b64encode( + _json.dumps({"type": "trace", "id": trace_id, "timestamp": trace_ts, "spanID": span_id}).encode() + ).decode("ascii") + trace_url = f"{LD_APP_URL}/projects/{LD_PROJECT_KEY}/traces?query={quote(f'trace_id={trace_id}')}&related_resource={quote(related)}" + trace_label = "β†— View Trace Waterfall" + elif trace_id: + query_param = quote(f"trace_id={trace_id}") + trace_url = f"{LD_APP_URL}/projects/{LD_PROJECT_KEY}/traces?query={query_param}" + trace_label = "β†— View Trace in LaunchDarkly" + else: + trace_url = f"{LD_APP_URL}/projects/{LD_PROJECT_KEY}/traces" + trace_label = "β†— Open Traces in LaunchDarkly" + + monitoring_url = f"{LD_APP_URL}/projects/{LD_PROJECT_KEY}/ai-configs/support-agent/monitoring" + + pii_html = "" + if security.get("detected") and security.get("redacted"): + escaped_redacted = html.escape(security["redacted"]) + pii_types = html.escape(", ".join(security.get("types") or [])) + pii_html = f'
PII redacted ({pii_types}): {escaped_redacted}
' + + summary = html.escape(f"{variation} ({model}){tools_summary}") + st.markdown( + f""" + {pii_html} +
+ Served: {summary} + + {trace_label} + β†— Monitoring & Metrics + +
+ """, + unsafe_allow_html=True, + ) + +EXAMPLE_QUERIES = [ + ("basic", "Basic Search", "How does Q-learning differ from SARSA in your knowledge base?"), + ("rerank", "RAG + Reranking", "In our textbook, how do multi-armed bandits balance exploration and exploitation? Search and rerank the passages."), + ("security", "Security Check", SECURITY_CHECK_QUERY), + ("arxiv", "ArXiv Research", "Find recent ArXiv papers on offline reinforcement learning"), + ("openalex", "OpenAlex Research", "Search OpenAlex for highly cited papers on reinforcement learning from human feedback"), + ("full", "Full Research Stack", "Compare how our textbook defines policy gradient methods with recent academic research papers"), +] -st.markdown("---") +st.markdown('

Example queries

', unsafe_allow_html=True) +for start in (0, 3): + columns = st.columns(3) + for column, (key, title, prompt) in zip(columns, EXAMPLE_QUERIES[start:start + 3]): + with column: + if st.button(title, key=f"ask-{key}", use_container_width=True): + st.session_state.example_query = prompt # Initialize session state with dual history for PII isolation if "messages" not in st.session_state: @@ -366,159 +427,67 @@ def process_tool_display(tools, tool_details): if "user_id" not in st.session_state: st.session_state.user_id = "user_other_paid_001" + +def send_feedback(message_id, feedback): + """Button callback, so a click on the newest response isn't lost on rerun.""" + message = next(m for m in st.session_state.messages if m.get("message_id") == message_id) + try: + feedback_response = requests.post( + f"{API_BASE_URL}/feedback", + json={ + "user_id": st.session_state.user_id, + "message_id": message_id, + "user_query": message.get("user_query", ""), + "ai_response": message["content"], + "feedback": feedback, + "variation_key": message["metadata"].get("primary_variation", "unknown"), + "model": message["metadata"].get("primary_model", "unknown"), + "tool_calls": message["metadata"].get("tools_used", []), + "source": "real_user", + "user_context": get_user_context(st.session_state.user_id, sample_users), + }, + ) + if feedback_response.status_code == 200: + message["feedback"] = feedback + else: + st.error("Failed to submit feedback") + except Exception as e: + st.error(f"Failed to submit feedback: {e}") + # Display chat history for message in st.session_state.messages: - with st.chat_message(message["role"]): + with st.chat_message(message["role"], avatar=str(USER_AVATAR if message["role"] == "user" else ASSISTANT_AVATAR)): st.write(message["content"]) - if message["role"] == "assistant" and "metadata" in message: + if message["role"] == "assistant": # Show feedback buttons for assistant messages - if "message_id" in message: - message_id = message["message_id"] - current_feedback = message.get("feedback") - - col1, col2, col3 = st.columns([1, 1, 8]) - with col1: - feedback_key = f"hist_thumbs_up_{message_id}" - disabled = current_feedback == "positive" - if st.button("πŸ‘", key=feedback_key, disabled=disabled, help="Helpful response"): - # Send feedback for historical message - try: - feedback_response = requests.post( - f"{API_BASE_URL}/feedback", - json={ - "user_id": st.session_state.user_id, - "message_id": message_id, - "user_query": message.get("user_query", ""), - "ai_response": message["content"], - "feedback": "positive", - "variation_key": message["metadata"].get("primary_variation", "unknown"), - "model": message["metadata"].get("primary_model", "unknown"), - "tool_calls": message["metadata"].get("tools_used", []), - "source": "real_user" - } - ) - if feedback_response.status_code == 200: - message["feedback"] = "positive" - st.rerun() - else: - st.error("Failed to submit feedback") - except Exception as e: - st.error(f"Failed to submit feedback: {e}") - - with col2: - feedback_key = f"hist_thumbs_down_{message_id}" - disabled = current_feedback == "negative" - if st.button("πŸ‘Ž", key=feedback_key, disabled=disabled, help="Not helpful"): - # Send feedback for historical message - try: - feedback_response = requests.post( - f"{API_BASE_URL}/feedback", - json={ - "user_id": st.session_state.user_id, - "message_id": message_id, - "user_query": message.get("user_query", ""), - "ai_response": message["content"], - "feedback": "negative", - "variation_key": message["metadata"].get("primary_variation", "unknown"), - "model": message["metadata"].get("primary_model", "unknown"), - "tool_calls": message["metadata"].get("tools_used", []), - "source": "real_user" - } - ) - if feedback_response.status_code == 200: - message["feedback"] = "negative" - st.rerun() - else: - st.error("Failed to submit feedback") - except Exception as e: - st.error(f"Failed to submit feedback: {e}") - - # Show current feedback status - if current_feedback: - feedback_emoji = "πŸ‘" if current_feedback == "positive" else "πŸ‘Ž" - st.caption(f"Feedback: {feedback_emoji}") - with st.expander("Workflow Details"): - metadata = message["metadata"] - if "agent_configurations" in metadata: - # Display each agent's configuration - for agent_config in metadata["agent_configurations"]: - st.markdown(f"**{agent_config['agent_name']}:**") - - # Process both available tools and tools used - tools_available = agent_config.get("tools", []) - tools_used = agent_config.get("tools_used", []) - tool_details = agent_config.get("tool_details", []) - - # Process tools used with details for display - processed_tools_used = process_tool_display(tools_used, tool_details) - - config_data = { - "model": agent_config["model"], - "variation_key": agent_config["variation_key"] - } - - # Show available tools if any - if tools_available: - config_data["tools_available"] = tools_available - - # Show tools actually used if any - if processed_tools_used: - config_data["tools_used"] = processed_tools_used - - # Show redacted text for supervisor agent only if PII was detected - if agent_config.get("agent_name") == "supervisor-agent": - # Look for redacted text from security agent in metadata - agent_data = metadata.get("agent_configurations", []) - for agent in agent_data: - if (agent.get("agent_name") == "security-agent" and - agent.get("detected") == True and - agent.get("redacted")): - config_data["redacted_text"] = agent.get("redacted", "") - break - - # Show PII findings for security agent - if agent_config.get("agent_name") == "security-agent": - # Show tools used (if any) - if tool_details: - for detail in tool_details: - if detail.get("name") == "pii_detection" and detail.get("pii_result"): - # Use the PII result directly from the tool (new schema format) - config_data["pii_analysis"] = detail["pii_result"] - - # Show security clearance status from agent response - # This will be passed from the API response - agent_data = metadata.get("agent_configurations", []) - for agent in agent_data: - if agent.get("agent_name") == "security-agent": - if agent.get("detected") is not None: - config_data["security_clearance"] = { - "detected": agent.get("detected"), - "types": agent.get("types", []), - "redacted": agent.get("redacted", "") - } - - st.json(config_data) - st.markdown("---") - else: - # Fallback for old format - st.json(metadata) - - with st.expander("Backend Console Output"): - if message["metadata"].get("console_logs"): - for log in message["metadata"]["console_logs"]: - st.code(log, language="text") - else: - st.markdown("*Console output not captured*") + message_id = message["message_id"] + current_feedback = message.get("feedback") + + col1, col2, col3 = st.columns([1, 1, 8]) + with col1: + st.button("πŸ‘", key=f"hist_thumbs_up_{message_id}", disabled=current_feedback == "positive", + help="Helpful response", on_click=send_feedback, args=(message_id, "positive")) + + with col2: + st.button("πŸ‘Ž", key=f"hist_thumbs_down_{message_id}", disabled=current_feedback == "negative", + help="Not helpful", on_click=send_feedback, args=(message_id, "negative")) + + # Show current feedback status + if current_feedback: + feedback_emoji = "πŸ‘" if current_feedback == "positive" else "πŸ‘Ž" + st.caption(f"Feedback: {feedback_emoji}") + + show_observability_links(message["metadata"]) # Handle input sources prompt = None # Check for example query first -if "example_query" in st.session_state and st.session_state.example_query: +if st.session_state.get("example_query"): prompt = st.session_state.example_query # Always show chat input - it should never disappear -user_text = st.chat_input("Ask questions about your documents or request research...") +user_text = st.chat_input(f"Ask about {KB_SUMMARY}, test PII redaction, or search ArXiv & OpenAlex...") if user_text is not None: user_text = user_text.strip() if user_text: @@ -530,272 +499,119 @@ def process_tool_display(tools, tool_details): if prompt: # Add user message st.session_state.messages.append({"role": "user", "content": prompt}) - + # Display user message - with st.chat_message("user"): + with st.chat_message("user", avatar=str(USER_AVATAR)): st.write(prompt) - - # Get agent response - try: - # Get user context for LaunchDarkly targeting - user_context = get_user_context(st.session_state.user_id, sample_users) - - # SECURITY BOUNDARY: Send only sanitized conversation history to API - # Raw messages (with PII) are never sent to backend - support agent isolation maintained - response = requests.post( - f"{API_BASE_URL}/chat", - json={ - "user_id": st.session_state.user_id, - "message": prompt, # Raw current message (security agent will process) - "user_context": user_context, - "sanitized_conversation_history": st.session_state.sanitized_messages # PII-free history only - } - ) - - if response.status_code == 200: - data = response.json() - - # Extract console logs if available - console_logs = data.get("console_logs", []) - - # SECURITY BOUNDARY: Extract sanitized messages from security agent - # Support agent only ever sees these PII-free versions - sanitized_user_message = prompt # Default fallback - - # Extract redacted user message from security agent output - if "agent_configurations" in data: - for agent_config in data["agent_configurations"]: + + # Get agent response inside the assistant bubble so a live spinner shows immediately + with st.chat_message("assistant", avatar=str(ASSISTANT_AVATAR)): + try: + user_context = get_user_context(st.session_state.user_id, sample_users) + + with st.spinner("Running multi-agent workflow (Supervisor β†’ Security β†’ Support + RAG/MCP tools)..."): + # SECURITY BOUNDARY: Send only sanitized conversation history to API + response = requests.post( + f"{API_BASE_URL}/chat", + json={ + "user_id": st.session_state.user_id, + "message": prompt, # Raw current message (security agent will process) + "user_context": user_context, + "sanitized_conversation_history": st.session_state.sanitized_messages # PII-free history only + } + ) + + if response.status_code == 200: + data = response.json() + + # SECURITY BOUNDARY: Extract sanitized messages from security agent + # Support agent only ever sees these PII-free versions + sanitized_user_message = prompt # Default fallback + + # Extract redacted user message from security agent output + for agent_config in data.get("agent_configurations") or []: if agent_config.get("agent_name") == "security-agent" and agent_config.get("redacted"): sanitized_user_message = agent_config["redacted"] break - - # Update sanitized conversation history (PII-free, for API calls) - st.session_state.sanitized_messages.append({ - "role": "user", - "content": sanitized_user_message # Redacted version only - }) - st.session_state.sanitized_messages.append({ - "role": "assistant", - "content": data["response"] - }) - - # Add assistant message with all agent configurations - metadata = { - "primary_variation": data["variation_key"], - "primary_model": data["model"], - "tools_used": data["tool_calls"], - "console_logs": console_logs - } - - # Add individual agent configurations if available - if "agent_configurations" in data and data["agent_configurations"]: - metadata["agent_configurations"] = data["agent_configurations"] - - # Add message with unique ID for feedback tracking - message_id = f"msg_{len(st.session_state.messages)}" - st.session_state.messages.append({ - "role": "assistant", - "content": data["response"], - "metadata": metadata, - "message_id": message_id, - "user_query": prompt, - "feedback": None - }) - - # Display assistant message - with st.chat_message("assistant"): + + # Update sanitized conversation history (PII-free, for API calls) + st.session_state.sanitized_messages.append({ + "role": "user", + "content": sanitized_user_message # Redacted version only + }) + st.session_state.sanitized_messages.append({ + "role": "assistant", + "content": data["response"] + }) + + # Add assistant message with all agent configurations + metadata = { + "primary_variation": data["variation_key"], + "primary_model": data["model"], + "tools_used": data["tool_calls"], + "trace_id": data.get("trace_id"), + "span_id": data.get("span_id"), + "trace_timestamp": data.get("trace_timestamp"), + "console_logs": data.get("console_logs", []), + "agent_configurations": data.get("agent_configurations") or [] + } + + # Add message with unique ID for feedback tracking + message_id = f"msg_{len(st.session_state.messages)}" + st.session_state.messages.append({ + "role": "assistant", + "content": data["response"], + "metadata": metadata, + "message_id": message_id, + "user_query": prompt, + "feedback": None + }) + st.write(data["response"]) - - # Add improved feedback system after the response - message_obj = None - for msg in st.session_state.messages: - if msg.get("message_id") == message_id: - message_obj = msg - break - - if message_obj: - current_feedback = message_obj.get("feedback") - - # Show feedback status if already provided - if current_feedback: - feedback_emoji = "πŸ‘" if current_feedback == "positive" else "πŸ‘Ž" - st.caption(f"Feedback recorded: {feedback_emoji}") - else: - # Show feedback options - st.markdown("**Was this response helpful?**") - col1, col2, col3 = st.columns([1, 1, 8]) - - with col1: - if st.button("πŸ‘ Helpful", key=f"new_thumbs_up_{message_id}", help="This response was helpful"): - # Send positive feedback to backend - try: - feedback_response = requests.post( - f"{API_BASE_URL}/feedback", - json={ - "user_id": st.session_state.user_id, - "message_id": message_id, - "user_query": prompt, - "ai_response": data["response"], - "feedback": "positive", - "variation_key": data["variation_key"], - "model": data["model"], - "tool_calls": data["tool_calls"], - "source": "real_user" - } - ) - if feedback_response.status_code == 200: - # Update message in session state immediately - for msg in st.session_state.messages: - if msg.get("message_id") == message_id: - msg["feedback"] = "positive" - break - # Force a rerun to update UI immediately - st.rerun() - else: - st.error("Failed to submit feedback") - except Exception as e: - st.error(f"Failed to submit feedback: {e}") - - with col2: - if st.button("πŸ‘Ž Not helpful", key=f"new_thumbs_down_{message_id}", help="This response was not helpful"): - # Send negative feedback to backend - try: - feedback_response = requests.post( - f"{API_BASE_URL}/feedback", - json={ - "user_id": st.session_state.user_id, - "message_id": message_id, - "user_query": prompt, - "ai_response": data["response"], - "feedback": "negative", - "variation_key": data["variation_key"], - "model": data["model"], - "tool_calls": data["tool_calls"], - "source": "real_user" - } - ) - if feedback_response.status_code == 200: - # Update message in session state immediately - for msg in st.session_state.messages: - if msg.get("message_id") == message_id: - msg["feedback"] = "negative" - break - # Force a rerun to update UI immediately - st.rerun() - else: - st.error("Failed to submit feedback") - except Exception as e: - st.error(f"Failed to submit feedback: {e}") - - with st.expander("Workflow Details"): - if "agent_configurations" in data and data["agent_configurations"]: - # Display each agent's configuration - for agent_config in data["agent_configurations"]: - st.markdown(f"**{agent_config['agent_name']}:**") - - # Process both available tools and tools used - tools_available = agent_config.get("tools", []) - tools_used = agent_config.get("tools_used", []) - tool_details = agent_config.get("tool_details", []) - - # Process tools used with details for display - processed_tools_used = process_tool_display(tools_used, tool_details) - - config_data = { - "model": agent_config["model"], - "variation_key": agent_config["variation_key"] - } - - # Show available tools if any - if tools_available: - config_data["tools_available"] = tools_available - - # Show tools actually used if any - if processed_tools_used: - config_data["tools_used"] = processed_tools_used - - # Show redacted text for supervisor agent only if PII was detected - if agent_config.get("agent_name") == "supervisor-agent": - # Look for redacted text from security agent in data - for agent in data["agent_configurations"]: - if (agent.get("agent_name") == "security-agent" and - agent.get("detected") == True and - agent.get("redacted")): - config_data["redacted_text"] = agent.get("redacted", "") - break - - # Show PII findings for security agent - if agent_config.get("agent_name") == "security-agent" and tool_details: - for detail in tool_details: - if detail.get("name") == "pii_detection" and detail.get("pii_result"): - # Use the PII result directly from the tool (new schema format) - config_data["pii_analysis"] = detail["pii_result"] - - st.json(config_data) - st.markdown("---") - else: - # Fallback to single configuration - use shared tool processing - tools_used = data.get("tool_calls", []) - # Convert old format to new format for compatibility - tool_details = [] - processed_tools = process_tool_display(tools_used, tool_details) - - config_data = { - "model": data["model"], - "variation_key": data["variation_key"] - } - - if processed_tools: - config_data["tools_used"] = processed_tools - - st.json(config_data) - - with st.expander("Backend Console Output"): - if metadata.get("console_logs"): - for log in metadata["console_logs"]: - st.code(log, language="text") - else: - st.markdown("*Console output not captured*") - - # Clear example query only after successful processing to avoid losing it on reruns - if "example_query" in st.session_state and st.session_state.example_query == prompt: - del st.session_state.example_query - else: - st.error(f"Error: {response.status_code}") - - except Exception as e: - st.error(f"Connection error: {e}") + + # Show feedback options + st.markdown("**Was this response helpful?**") + col1, col2, col3 = st.columns([1, 1, 8]) + + with col1: + st.button("πŸ‘ Helpful", key=f"new_thumbs_up_{message_id}", help="This response was helpful", + on_click=send_feedback, args=(message_id, "positive")) + + with col2: + st.button("πŸ‘Ž Not helpful", key=f"new_thumbs_down_{message_id}", help="This response was not helpful", + on_click=send_feedback, args=(message_id, "negative")) + + show_observability_links(metadata) + + # Clear example query only after successful processing to avoid losing it on reruns + if st.session_state.get("example_query") == prompt: + del st.session_state.example_query + else: + st.error(f"Error: {response.status_code}") + + except Exception as e: + st.error(f"Connection error: {e}") # Sidebar for user settings with st.sidebar: st.header("Context") - - # User ID selection with improved styling + user_options = [user['id'] for user in sample_users] - # Find default index for user_other_paid_001 - default_index = 0 - if "user_other_paid_001" in user_options: - default_index = user_options.index("user_other_paid_001") - elif st.session_state.user_id in user_options: - default_index = user_options.index(st.session_state.user_id) - - selected_user_id = st.selectbox("User ID", user_options, index=default_index, + selected_user_id = st.selectbox("User ID", user_options, index=user_options.index("user_other_paid_001"), help="Different User IDs may receive different AI configurations via LaunchDarkly") - + # Show user context for selected user - if sample_users: - user_context = get_user_context(selected_user_id, sample_users) - st.caption(f"Context: {user_context['country']} {user_context['plan']} user") - + user_context = get_user_context(selected_user_id, sample_users) + st.caption(f"Context: {user_context['country']} {user_context['plan']} user") + if selected_user_id != st.session_state.user_id: st.session_state.user_id = selected_user_id # Clear both message histories when switching users st.session_state.messages = [] st.session_state.sanitized_messages = [] st.rerun() - + if st.button("Clear Chat"): st.session_state.messages = [] st.session_state.sanitized_messages = [] st.rerun() - diff --git a/utils/bedrock_helpers.py b/utils/bedrock_helpers.py index 4d7c090..1ed6928 100644 --- a/utils/bedrock_helpers.py +++ b/utils/bedrock_helpers.py @@ -1,40 +1,11 @@ """ -Bedrock provider and model ID normalization utilities. +Bedrock model ID utilities. -Handles provider format variations (Bedrock, bedrock:anthropic, anthropic). Auto-corrects direct model IDs to inference profiles to prevent Bedrock errors. """ +import os -from utils.logger import log_debug - - -def normalize_bedrock_provider(provider_name: str) -> str: - """ - Normalize Bedrock provider formats to 'bedrock' for LangChain. - - Handles: Bedrock, bedrock:anthropic, anthropic β†’ bedrock - """ - if not provider_name: - return provider_name - - lower_provider = provider_name.lower() - - # Handle bedrock:* format (e.g., "bedrock:anthropic" from structured output) - if lower_provider.startswith('bedrock:'): - log_debug(f"BEDROCK HELPER: Normalized '{provider_name}' β†’ 'bedrock'") - return 'bedrock' - - # Handle explicit "Bedrock" or "bedrock" - if lower_provider == 'bedrock': - return 'bedrock' - - # Handle legacy "anthropic" routing to Bedrock - if lower_provider == 'anthropic': - log_debug("BEDROCK HELPER: Routing 'anthropic' β†’ 'bedrock'") - return 'bedrock' - - # Return as-is for other providers - return lower_provider +from utils.logger import log_debug, log_student def is_inference_profile_id(model_id: str) -> bool: @@ -43,101 +14,46 @@ def is_inference_profile_id(model_id: str) -> bool: return False # Inference profiles start with region prefix - region_prefixes = ['us.', 'eu.', 'ap.', 'ca.', 'sa.', 'af.', 'me.'] - return any(model_id.startswith(prefix) for prefix in region_prefixes) - - -def extract_base_model_from_inference_profile(inference_profile_id: str) -> str: - """ - Extract base model name from inference profile for pricing. - - us.anthropic.claude-sonnet-4-6-v2:0 β†’ claude-sonnet-4-6 - """ - if not inference_profile_id: - return inference_profile_id - - # Remove region prefix (e.g., "us.", "eu.") - parts = inference_profile_id.split('.', 1) - if len(parts) < 2: - return inference_profile_id - - # Remove provider prefix (e.g., "anthropic.") - model_with_version = parts[1] - provider_parts = model_with_version.split('.', 1) - if len(provider_parts) < 2: - return inference_profile_id - - # Now we have something like "claude-sonnet-4-6-v2:0" - full_model = provider_parts[1] - - # Map to base model name for pricing - # Extract model family before version suffix - model_base = full_model.rsplit('-', 1)[0] if '-v' in full_model or ':' in full_model else full_model - - # Map specific versions to pricing model names - model_mapping = { - 'claude-sonnet-4-6': 'claude-sonnet-4-6', - 'claude-3-5-sonnet-20250219': 'claude-3-5-sonnet-latest', - 'claude-3-7-sonnet-20250219': 'claude-sonnet-4-6', - 'claude-haiku-4-5-20251001': 'claude-haiku-4-5-20251001', - 'claude-opus-4-7': 'claude-opus-4-7', - } - - return model_mapping.get(model_base, model_base) + region_prefixes = ('us.', 'us-gov.', 'eu.', 'ap.', 'apac.', 'au.', 'jp.', 'ca.', 'sa.', 'af.', 'me.', 'global.') + return model_id.startswith(region_prefixes) def ensure_bedrock_inference_profile(model_id: str, aws_region: str = None) -> str: """ Auto-correct direct Bedrock model IDs to inference profiles. - anthropic.claude-* β†’ {region}.anthropic.claude-* + claude-* β†’ anthropic.claude-* β†’ {region}.anthropic.claude-* Region from: BEDROCK_INFERENCE_REGION env var, AWS_REGION, or default 'us' """ - import os + # Anthropic model names (the "Anthropic" provider in LaunchDarkly) become Bedrock model IDs + if model_id.startswith('claude-'): + model_id = f"anthropic.{model_id}" # Already an inference profile - return as-is if is_inference_profile_id(model_id): log_debug(f"BEDROCK: Model ID '{model_id}' is already an inference profile") return model_id - # Determine region prefix # Priority: BEDROCK_INFERENCE_REGION > AWS_REGION > default "us" region_prefix = os.getenv('BEDROCK_INFERENCE_REGION') - if not region_prefix: # Extract from AWS_REGION (e.g., us-east-1 β†’ us) - if aws_region: - region_prefix = aws_region.split('-')[0] - else: - region_from_env = os.getenv('AWS_REGION', 'us-east-1') - region_prefix = region_from_env.split('-')[0] + region_prefix = (aws_region or os.getenv('AWS_REGION', 'us-east-1')).split('-')[0] # Auto-correct direct model IDs to inference profiles - if model_id.startswith('anthropic.') or model_id.startswith('amazon.') or model_id.startswith('meta.'): - # Convert: anthropic.claude-3-7-sonnet-20250219-v1:0 - # To: us.anthropic.claude-3-7-sonnet-20250219-v1:0 + if model_id.startswith(('anthropic.', 'amazon.', 'meta.')): + # Convert: anthropic.claude-haiku-5-5 + # To: us.anthropic.claude-haiku-5-5 inference_profile_id = f"{region_prefix}.{model_id}" - from utils.logger import log_student log_student("BEDROCK AUTO-CORRECT: Converted direct model ID to inference profile") log_student(f" Original: {model_id}") log_student(f" Corrected: {inference_profile_id}") log_student(f" Region Prefix: {region_prefix}") - log_student(f" πŸ’‘ TIP: Update your LaunchDarkly AI Config to use '{inference_profile_id}' directly") + log_student(f" πŸ’‘ TIP: Select Bedrock β†’ {inference_profile_id} in your LaunchDarkly config to use it directly") return inference_profile_id # Unknown format - return as-is and let Bedrock handle it log_debug(f"BEDROCK: Model ID '{model_id}' format not recognized, using as-is") return model_id - - -def get_bedrock_validation_guidance(model_id: str) -> str: - """Provide guidance for Bedrock model configuration issues.""" - if not is_inference_profile_id(model_id): - return ( - f"⚠️ BEDROCK CONFIG ERROR: '{model_id}' is a direct model ID.\n" - f" Update to inference profile format: 'us.anthropic.claude-*'\n" - f" Set BEDROCK_INFERENCE_REGION in .env to control region prefix." - ) - return "" diff --git a/utils/cost_calculator.py b/utils/cost_calculator.py index 18c775a..dad136d 100644 --- a/utils/cost_calculator.py +++ b/utils/cost_calculator.py @@ -1,146 +1,37 @@ """ Cost Calculator for AI Model Usage -Hybrid pricing: exact match β†’ normalize inference profiles β†’ pattern match by tier β†’ return $0 -Handles new Bedrock models automatically via pattern matching (Opus/Sonnet/Haiku tiers). +Prices are USD per 1 million tokens, from the LaunchDarkly model catalog. Mistral +is $0 because the tutorial uses Mistral's free tier. """ -# Model pricing per 1 million tokens (in USD) MODEL_PRICING = { - # OpenAI Models - "gpt-4o": {"input": 6.00, "output": 18.00}, - "gpt-4o-mini": {"input": 0.15, "output": 0.60}, - "gpt-4o-mini-2024-07-18": {"input": 0.15, "output": 0.60}, - "chatgpt-4o-latest": {"input": 6.00, "output": 18.00}, - - # Anthropic Claude Models - "claude-sonnet-4-6": {"input": 3.00, "output": 15.00}, - "claude-haiku-4-5-20251001": {"input": 0.25, "output": 1.25}, - "claude-3-5-sonnet-latest": {"input": 3.00, "output": 15.00}, - "claude-opus-4-7": {"input": 15.00, "output": 75.00}, - - # Mistral Models (Free as specified) + "claude-haiku-5-5": {"input": 0.10, "output": 0.50}, + "claude-sonnet-5-5": {"input": 2.00, "output": 10.00}, + "claude-opus-5-5": {"input": 4.00, "output": 20.00}, + "gpt-6-luna": {"input": 0.10, "output": 0.50}, + "gpt-6.1-terra": {"input": 1.00, "output": 5.00}, + "gpt-6.2-sol": {"input": 2.00, "output": 10.00}, "mistral-small-latest": {"input": 0.0, "output": 0.0}, - "mistral-small": {"input": 0.0, "output": 0.0}, - "mistral-medium": {"input": 0.0, "output": 0.0}, - "mistral-large": {"input": 0.0, "output": 0.0}, - - # LaunchDarkly Provider-Prefixed Names (from create_configs.py mapping) - "Anthropic.claude-sonnet-4-6": {"input": 3.00, "output": 15.00}, - "Anthropic.claude-haiku-4-5-20251001": {"input": 0.25, "output": 1.25}, - "Anthropic.claude-opus-4-7": {"input": 15.00, "output": 75.00}, - "OpenAI.gpt-4o": {"input": 6.00, "output": 18.00}, - "OpenAI.gpt-4o-mini-2024-07-18": {"input": 0.15, "output": 0.60}, - "Mistral.mistral-small-latest": {"input": 0.0, "output": 0.0}, } - -def get_pricing_by_pattern(model_name: str) -> dict: - """ - Pattern match model tier for pricing (Opus/Sonnet/Haiku/GPT-4). - - Handles new Bedrock models automatically without code changes. - Returns None if no pattern matches. - """ - # Normalize: lowercase and remove common prefixes - normalized = model_name.lower() - normalized = normalized.replace('us.', '').replace('eu.', '').replace('ap.', '') - normalized = normalized.replace('ca.', '').replace('sa.', '').replace('af.', '').replace('me.', '') - normalized = normalized.replace('anthropic.', '').replace('amazon.', '').replace('meta.', '') - - # Anthropic Claude - Match by tier - if 'opus' in normalized: - return {"input": 15.00, "output": 75.00} # Opus tier (flagship) - elif 'sonnet' in normalized or 'claude-4' in normalized: - return {"input": 3.00, "output": 15.00} # Sonnet tier (balanced) - elif 'haiku' in normalized: - return {"input": 0.25, "output": 1.25} # Haiku tier (fast) - - # OpenAI - Match by tier - elif 'gpt-4o-mini' in normalized: - return {"input": 0.15, "output": 0.60} # GPT-4o-mini - elif 'gpt-4' in normalized or 'gpt4' in normalized: - return {"input": 6.00, "output": 18.00} # GPT-4 tier - - # Mistral - Free tier - elif 'mistral' in normalized: - return {"input": 0.0, "output": 0.0} # Free tier - - # No pattern match - return None +# Bedrock model IDs carry region and version affixes, so price them by Claude tier. +TIER_PRICING = { + "opus": MODEL_PRICING["claude-opus-5-5"], + "sonnet": MODEL_PRICING["claude-sonnet-5-5"], + "haiku": MODEL_PRICING["claude-haiku-5-5"], +} def calculate_cost(model_name: str, input_tokens: int, output_tokens: int) -> float: - """ - Calculate cost in USD for token usage. - - Hybrid strategy: exact match β†’ normalize β†’ pattern match β†’ $0 - Handles new Bedrock models automatically via tier matching. - """ - pricing = None - lookup_name = model_name - match_type = None - - # Step 1: Try exact match in pricing table - if model_name in MODEL_PRICING: - pricing = MODEL_PRICING[model_name] - lookup_name = model_name - match_type = "exact" - - # Step 2: Try normalizing Bedrock inference profiles - elif model_name not in MODEL_PRICING: - from utils.bedrock_helpers import is_inference_profile_id, extract_base_model_from_inference_profile - - if is_inference_profile_id(model_name): - lookup_name = extract_base_model_from_inference_profile(model_name) - if lookup_name in MODEL_PRICING: - pricing = MODEL_PRICING[lookup_name] - match_type = "normalized" - - # Step 3: Try pattern-based fallback - if pricing is None: - pricing = get_pricing_by_pattern(model_name) - if pricing is not None: - lookup_name = model_name - match_type = "pattern" - - # Step 4: Graceful degradation - return 0 for unknown models + """Calculate cost in USD for token usage. Unknown models cost $0.""" + pricing = MODEL_PRICING.get(model_name) or next( + (price for tier, price in TIER_PRICING.items() if tier in model_name.lower()), None + ) if pricing is None: print(f"πŸ’‘ COST CALCULATOR: No pricing available for '{model_name}' (cost tracking skipped)") return 0.0 - # Calculate cost - input_cost = (input_tokens / 1_000_000) * pricing["input"] - output_cost = (output_tokens / 1_000_000) * pricing["output"] - total_cost = input_cost + output_cost - - # Log calculation with match type for transparency - if match_type == "pattern": - print(f"COST CALCULATED: ${total_cost:.6f} for {model_name} ({input_tokens} in, {output_tokens} out) [pattern match]") - else: - print(f"COST CALCULATED: ${total_cost:.6f} for {lookup_name} ({input_tokens} in, {output_tokens} out)") - - return round(total_cost, 6) # Round to 6 decimal places for precision - - -def get_model_pricing(model_name: str) -> dict: - """ - Get pricing information for a specific model. - - Args: - model_name: Name of the AI model - - Returns: - Dictionary with input and output pricing per 1M tokens - """ - return MODEL_PRICING.get(model_name, {"input": 0.0, "output": 0.0}) - - -def list_supported_models() -> list: - """ - Get list of all supported models. - - Returns: - List of model names with pricing information - """ - return list(MODEL_PRICING.keys()) \ No newline at end of file + total_cost = (input_tokens * pricing["input"] + output_tokens * pricing["output"]) / 1_000_000 + print(f"COST CALCULATED: ${total_cost:.6f} for {model_name} ({input_tokens} in, {output_tokens} out)") + return round(total_cost, 6) diff --git a/utils/logger.py b/utils/logger.py index 5e6f181..7c08804 100644 --- a/utils/logger.py +++ b/utils/logger.py @@ -1,5 +1,9 @@ import os from typing import Any +from dotenv import load_dotenv + +# Modules import this logger before they load .env, so load it here for LOG_MODE +load_dotenv() # Get log mode from environment variable (default to STUDENT for educational clarity) LOG_MODE = os.getenv('LOG_MODE', 'STUDENT').upper() @@ -12,20 +16,3 @@ def log_debug(*args: Any, **kwargs: Any) -> None: """Log debug messages - only shown in DEBUG mode""" if LOG_MODE == 'DEBUG': print(*args, **kwargs) - -def log_info(*args: Any, **kwargs: Any) -> None: - """Log informational messages - shown in STUDENT and DEBUG modes""" - if LOG_MODE in ['STUDENT', 'DEBUG']: - print(*args, **kwargs) - -def log_verbose(*args: Any, **kwargs: Any) -> None: - """Log verbose technical details - only shown in DEBUG mode""" - if LOG_MODE == 'DEBUG': - print(*args, **kwargs) - -# Helper function to check current log mode -def is_student_mode() -> bool: - return LOG_MODE == 'STUDENT' - -def is_debug_mode() -> bool: - return LOG_MODE == 'DEBUG' \ No newline at end of file diff --git a/utils/metrics.py b/utils/metrics.py deleted file mode 100644 index 99ecb12..0000000 --- a/utils/metrics.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Metrics tracking utilities for supervisor agent orchestration""" - -import functools -from typing import Callable, Any, Optional -from utils.logger import log_debug - - -def track_supervisor_metrics(metric_name: str, config_manager: Any, supervisor_config: Any): - """Decorator to track supervisor metrics with error handling""" - def decorator(func: Callable) -> Callable: - @functools.wraps(func) - def wrapper(*args, **kwargs): - try: - # Track operation start - config_manager.track_metrics( - supervisor_config.create_tracker(), - lambda: f"{metric_name}_start", - model_name=supervisor_config.model.name if hasattr(supervisor_config, 'model') else None - ) - - # Execute function - result = func(*args, **kwargs) - - # Track successful completion - config_manager.track_metrics( - supervisor_config.create_tracker(), - lambda: f"{metric_name}_success", - model_name=supervisor_config.model.name if hasattr(supervisor_config, 'model') else None - ) - - return result - - except Exception as e: - log_debug(f"SUPERVISOR ERROR in {metric_name}: {e}") - - # Track error with LDAI metrics - config_manager.track_metrics( - supervisor_config.create_tracker(), - lambda: (_ for _ in ()).throw(e), # Trigger error tracking - model_name=supervisor_config.model.name if hasattr(supervisor_config, 'model') else None - ) - raise - return wrapper - return decorator - - -def track_supervisor_decision(config_manager: Any, supervisor_config: Any, next_agent: str): - """Helper to track supervisor routing decisions""" - config_manager.track_metrics( - supervisor_config.create_tracker(), - lambda: f"supervisor_decision_success_{next_agent}", - model_name=supervisor_config.model.name if hasattr(supervisor_config, 'model') else None - ) - - -def track_workflow_completion(config_manager: Any, supervisor_config: Any, tool_calls: list): - """Helper to track supervisor workflow completion""" - config_manager.track_metrics( - supervisor_config.create_tracker(), - lambda: f"supervisor_workflow_complete_tools_{len(tool_calls)}", - model_name=supervisor_config.model.name if hasattr(supervisor_config, 'model') else None - ) - - -def track_agent_orchestration(config_manager: Any, supervisor_config: Any, agent_name: str): - """Helper to track agent orchestration start""" - # Track orchestration start - config_manager.track_metrics( - supervisor_config.create_tracker(), - lambda: f"supervisor_orchestrating_{agent_name}_start", - model_name=supervisor_config.model.name if hasattr(supervisor_config, 'model') else None - ) - - -def track_agent_success(config_manager: Any, supervisor_config: Any, agent_name: str, tool_calls: Optional[list] = None): - """Helper to track agent orchestration success""" - if tool_calls is not None: - config_manager.track_metrics( - supervisor_config.create_tracker(), - lambda: f"supervisor_orchestrating_{agent_name}_success_tools_{len(tool_calls)}", - model_name=supervisor_config.model.name if hasattr(supervisor_config, 'model') else None - ) - else: - config_manager.track_metrics( - supervisor_config.create_tracker(), - lambda: f"supervisor_orchestrating_{agent_name}_success", - model_name=supervisor_config.model.name if hasattr(supervisor_config, 'model') else None - ) \ No newline at end of file diff --git a/utils/pii_sanitizer.py b/utils/pii_sanitizer.py deleted file mode 100644 index 7e0b1d4..0000000 --- a/utils/pii_sanitizer.py +++ /dev/null @@ -1,115 +0,0 @@ -"""PII sanitization utilities for multi-agent workflows""" - -from typing import List, Dict, Any -from langchain_core.messages import HumanMessage, AIMessage, BaseMessage -from utils.logger import log_debug, log_verbose - - -def sanitize_messages(original_messages: List[BaseMessage], redacted_text: str) -> List[BaseMessage]: - """ - Create sanitized message history by replacing PII in human messages with redacted text - - Args: - original_messages: Original message history that may contain PII - redacted_text: Clean text with PII removed/redacted - - Returns: - List of sanitized messages safe for downstream agents - """ - sanitized_messages = [] - - log_debug(f"πŸ”’ PII PROTECTION: Sanitizing {len(original_messages)} messages") - - for msg in original_messages: - if isinstance(msg, HumanMessage): - # Replace human message content with redacted text - sanitized_msg = HumanMessage(content=redacted_text) - sanitized_messages.append(sanitized_msg) - log_verbose(f"πŸ”’ PII SANITIZED: Original '{msg.content[:50]}...' -> Redacted '{redacted_text[:50]}...'") - else: - # Keep other message types as-is - sanitized_messages.append(msg) - - log_verbose(f"πŸ”’ PII PROTECTION: Created {len(sanitized_messages)} sanitized messages for downstream agents") - return sanitized_messages - - -def create_redacted_input(user_input: str, processed_input: str, pii_detected: bool, pii_types: List[str]) -> str: - """ - Create safe input text for downstream agents - - Args: - user_input: Original user input - processed_input: Processed/redacted input from security agent - pii_detected: Whether PII was detected - pii_types: Types of PII found - - Returns: - Safe text to pass to downstream agents - """ - if pii_detected and pii_types: - log_debug(f"PII TYPES FOUND: {pii_types}") - return processed_input - return user_input - - -def prepare_safe_agent_input(state: Dict[str, Any], agent_type: str) -> Dict[str, Any]: - """ - Prepare sanitized input for downstream agents (security or support) - - Args: - state: Current workflow state - agent_type: Type of agent ("security" or "support") - - Returns: - Safe agent input dictionary - """ - if agent_type == "security": - # Security agent gets original input for analysis - return { - "user_input": state["user_input"], - "response": "", - "tool_calls": [], - "messages": [HumanMessage(content=state["messages"][-2].content if len(state["messages"]) >= 2 else state["user_input"])] - } - - elif agent_type == "support": - # Support agent gets sanitized input - processed_input = state.get("processed_user_input", state["user_input"]) - sanitized_messages = state.get("sanitized_messages", []) - - # Use sanitized message history to prevent PII leakage - if sanitized_messages: - support_messages = sanitized_messages - log_debug(f"πŸ”’ SECURITY ENFORCED: Using {len(sanitized_messages)} sanitized messages for support agent") - # Log what the support agent will actually see - for i, msg in enumerate(sanitized_messages): - msg_preview = msg.content[:50] if hasattr(msg, 'content') else str(msg)[:50] - log_debug(f"πŸ”’ SUPPORT MSG {i}: {type(msg).__name__} - '{msg_preview}...'") - else: - # Fallback: create clean message with only redacted text - support_messages = [HumanMessage(content=processed_input)] - log_debug(f"FALLBACK: No sanitized messages, using redacted text only") - - return { - "user_input": processed_input, # Use redacted text if PII was found - "response": "", - "tool_calls": [], - "tool_details": [], - "messages": support_messages # CRITICAL: Only sanitized messages passed to support agent - } - - else: - raise ValueError(f"Unknown agent type: {agent_type}") - - -def log_pii_status(state: Dict[str, Any]) -> None: - """Log PII detection status for debugging""" - pii_detected = state.get("pii_detected", False) - pii_types = state.get("pii_types", []) - processed_input = state.get("processed_user_input", state["user_input"]) - - log_debug(f"πŸ”’ SUPERVISOR: Passing to support agent - PII detected: {pii_detected}") - log_debug(f"SUPERVISOR: Input text: '{processed_input[:100]}...'") - if pii_types: - log_debug(f"SUPERVISOR: PII types found: {pii_types}") \ No newline at end of file diff --git a/uv.lock b/uv.lock index 17b2775..b8352c0 100644 --- a/uv.lock +++ b/uv.lock @@ -1,10 +1,6 @@ version = 1 revision = 3 -requires-python = ">=3.11" -resolution-markers = [ - "python_full_version >= '3.12'", - "python_full_version < '3.12'", -] +requires-python = ">=3.12" [[package]] name = "agents-demo" @@ -22,11 +18,10 @@ dependencies = [ { name = "langchain-mistralai" }, { name = "langchain-openai" }, { name = "langgraph" }, + { name = "launchdarkly-ai-server", extra = ["otel"] }, { name = "launchdarkly-server-sdk" }, - { name = "launchdarkly-server-sdk-ai" }, { name = "mcp" }, - { name = "numpy", version = "1.26.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "numpy", version = "2.3.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "numpy" }, { name = "openai" }, { name = "pydantic" }, { name = "pymupdf" }, @@ -34,7 +29,6 @@ dependencies = [ { name = "pyyaml" }, { name = "rank-bm25" }, { name = "requests" }, - { name = "semanticscholar" }, { name = "streamlit" }, { name = "tiktoken" }, { name = "uvicorn", extra = ["standard"] }, @@ -60,8 +54,8 @@ requires-dist = [ { name = "langchain-mistralai", specifier = ">=0.2.12" }, { name = "langchain-openai", specifier = ">=0.3.31" }, { name = "langgraph", specifier = ">=0.0.40" }, - { name = "launchdarkly-server-sdk", specifier = ">=9.0.0" }, - { name = "launchdarkly-server-sdk-ai", specifier = ">=0.20.0" }, + { name = "launchdarkly-ai-server", extras = ["otel"], specifier = ">=1.1.0" }, + { name = "launchdarkly-server-sdk", specifier = ">=9.18.4" }, { name = "mcp", specifier = ">=1.13.1" }, { name = "numpy", specifier = ">=1.24.0" }, { name = "openai", specifier = ">=1.0.0" }, @@ -71,7 +65,6 @@ requires-dist = [ { name = "pyyaml", specifier = ">=6.0" }, { name = "rank-bm25", specifier = ">=0.2.2" }, { name = "requests", specifier = ">=2.31.0" }, - { name = "semanticscholar", specifier = ">=0.10.0" }, { name = "streamlit", specifier = ">=1.28.0" }, { name = "tiktoken", specifier = ">=0.5.0" }, { name = "uvicorn", extras = ["standard"], specifier = ">=0.24.0" }, @@ -211,11 +204,11 @@ wheels = [ [[package]] name = "certifi" -version = "2025.8.3" +version = "2026.10.23" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/dc/67/960ebe6bf230a96cda2e0abcf73af550ec4f090005363542f0765df162e0/certifi-2025.8.3.tar.gz", hash = "sha256:e564105f78ded564e3ae7c923924435e1daa7463faeab5bb932bc53ffae63407", size = 162386, upload-time = "2025-08-03T03:07:47.08Z" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/e5/48/1549795ba7742c948d2ad169c1c8cdbae65bc450d6cd753d124b17c8cd32/certifi-2025.8.3-py3-none-any.whl", hash = "sha256:f6c12493cfb1b06ba2ff328595af9350c65d6644968e5d3a2ffd78699af217a5", size = 161216, upload-time = "2025-08-03T03:07:45.777Z" }, + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, ] [[package]] @@ -224,17 +217,6 @@ version = "3.4.3" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/83/2d/5fd176ceb9b2fc619e63405525573493ca23441330fcdaee6bef9460e924/charset_normalizer-3.4.3.tar.gz", hash = "sha256:6fce4b8500244f6fcb71465d4a4930d132ba9ab8e71a7859e6a5d59851068d14", size = 122371, upload-time = "2025-08-09T07:57:28.46Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7f/b5/991245018615474a60965a7c9cd2b4efbaabd16d582a5547c47ee1c7730b/charset_normalizer-3.4.3-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:b256ee2e749283ef3ddcff51a675ff43798d92d746d1a6e4631bf8c707d22d0b", size = 204483, upload-time = "2025-08-09T07:55:53.12Z" }, - { url = "https://files.pythonhosted.org/packages/c7/2a/ae245c41c06299ec18262825c1569c5d3298fc920e4ddf56ab011b417efd/charset_normalizer-3.4.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:13faeacfe61784e2559e690fc53fa4c5ae97c6fcedb8eb6fb8d0a15b475d2c64", size = 145520, upload-time = "2025-08-09T07:55:54.712Z" }, - { url = "https://files.pythonhosted.org/packages/3a/a4/b3b6c76e7a635748c4421d2b92c7b8f90a432f98bda5082049af37ffc8e3/charset_normalizer-3.4.3-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:00237675befef519d9af72169d8604a067d92755e84fe76492fef5441db05b91", size = 158876, upload-time = "2025-08-09T07:55:56.024Z" }, - { url = "https://files.pythonhosted.org/packages/e2/e6/63bb0e10f90a8243c5def74b5b105b3bbbfb3e7bb753915fe333fb0c11ea/charset_normalizer-3.4.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:585f3b2a80fbd26b048a0be90c5aae8f06605d3c92615911c3a2b03a8a3b796f", size = 156083, upload-time = "2025-08-09T07:55:57.582Z" }, - { url = "https://files.pythonhosted.org/packages/87/df/b7737ff046c974b183ea9aa111b74185ac8c3a326c6262d413bd5a1b8c69/charset_normalizer-3.4.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0e78314bdc32fa80696f72fa16dc61168fda4d6a0c014e0380f9d02f0e5d8a07", size = 150295, upload-time = "2025-08-09T07:55:59.147Z" }, - { url = "https://files.pythonhosted.org/packages/61/f1/190d9977e0084d3f1dc169acd060d479bbbc71b90bf3e7bf7b9927dec3eb/charset_normalizer-3.4.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:96b2b3d1a83ad55310de8c7b4a2d04d9277d5591f40761274856635acc5fcb30", size = 148379, upload-time = "2025-08-09T07:56:00.364Z" }, - { url = "https://files.pythonhosted.org/packages/4c/92/27dbe365d34c68cfe0ca76f1edd70e8705d82b378cb54ebbaeabc2e3029d/charset_normalizer-3.4.3-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:939578d9d8fd4299220161fdd76e86c6a251987476f5243e8864a7844476ba14", size = 160018, upload-time = "2025-08-09T07:56:01.678Z" }, - { url = "https://files.pythonhosted.org/packages/99/04/baae2a1ea1893a01635d475b9261c889a18fd48393634b6270827869fa34/charset_normalizer-3.4.3-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:fd10de089bcdcd1be95a2f73dbe6254798ec1bda9f450d5828c96f93e2536b9c", size = 157430, upload-time = "2025-08-09T07:56:02.87Z" }, - { url = "https://files.pythonhosted.org/packages/2f/36/77da9c6a328c54d17b960c89eccacfab8271fdaaa228305330915b88afa9/charset_normalizer-3.4.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:1e8ac75d72fa3775e0b7cb7e4629cec13b7514d928d15ef8ea06bca03ef01cae", size = 151600, upload-time = "2025-08-09T07:56:04.089Z" }, - { url = "https://files.pythonhosted.org/packages/64/d4/9eb4ff2c167edbbf08cdd28e19078bf195762e9bd63371689cab5ecd3d0d/charset_normalizer-3.4.3-cp311-cp311-win32.whl", hash = "sha256:6cf8fd4c04756b6b60146d98cd8a77d0cdae0e1ca20329da2ac85eed779b6849", size = 99616, upload-time = "2025-08-09T07:56:05.658Z" }, - { url = "https://files.pythonhosted.org/packages/f4/9c/996a4a028222e7761a96634d1820de8a744ff4327a00ada9c8942033089b/charset_normalizer-3.4.3-cp311-cp311-win_amd64.whl", hash = "sha256:31a9a6f775f9bcd865d88ee350f0ffb0e25936a7f930ca98995c05abf1faf21c", size = 107108, upload-time = "2025-08-09T07:56:07.176Z" }, { url = "https://files.pythonhosted.org/packages/e9/5e/14c94999e418d9b87682734589404a25854d5f5d0408df68bc15b6ff54bb/charset_normalizer-3.4.3-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:e28e334d3ff134e88989d90ba04b47d84382a828c061d0d1027b1b12a62b39b1", size = 205655, upload-time = "2025-08-09T07:56:08.475Z" }, { url = "https://files.pythonhosted.org/packages/7d/a8/c6ec5d389672521f644505a257f50544c074cf5fc292d5390331cd6fc9c3/charset_normalizer-3.4.3-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0cacf8f7297b0c4fcb74227692ca46b4a5852f8f4f24b3c766dd94a1075c4884", size = 146223, upload-time = "2025-08-09T07:56:09.708Z" }, { url = "https://files.pythonhosted.org/packages/fc/eb/a2ffb08547f4e1e5415fb69eb7db25932c52a52bed371429648db4d84fb1/charset_normalizer-3.4.3-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c6fd51128a41297f5409deab284fecbe5305ebd7e5a1f959bee1c054622b7018", size = 159366, upload-time = "2025-08-09T07:56:11.326Z" }, @@ -271,15 +253,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8a/1f/f041989e93b001bc4e44bb1669ccdcf54d3f00e628229a85b08d330615c5/charset_normalizer-3.4.3-py3-none-any.whl", hash = "sha256:ce571ab16d890d23b5c278547ba694193a45011ff86a9162a71307ed9f86759a", size = 53175, upload-time = "2025-08-09T07:57:26.864Z" }, ] -[[package]] -name = "chevron" -version = "0.14.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/15/1f/ca74b65b19798895d63a6e92874162f44233467c9e7c1ed8afd19016ebe9/chevron-0.14.0.tar.gz", hash = "sha256:87613aafdf6d77b6a90ff073165a61ae5086e21ad49057aa0e53681601800ebf", size = 11440, upload-time = "2021-01-02T22:47:59.233Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/52/93/342cc62a70ab727e093ed98e02a725d85b746345f05d2b5e5034649f4ec8/chevron-0.14.0-py3-none-any.whl", hash = "sha256:fbf996a709f8da2e745ef763f482ce2d311aa817d287593a5b990d6d6e4f0443", size = 11595, upload-time = "2021-01-02T22:47:57.847Z" }, -] - [[package]] name = "click" version = "8.2.1" @@ -310,34 +283,16 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/12/b3/231ffd4ab1fc9d679809f356cebee130ac7daa00d6d6f3206dd4fd137e9e/distro-1.9.0-py3-none-any.whl", hash = "sha256:7bffd925d65168f85027d8da9af6bddab658135b840670a223589bc0c8ef02b2", size = 20277, upload-time = "2023-12-24T09:54:30.421Z" }, ] -[[package]] -name = "expiringdict" -version = "1.2.2" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/fc/62/c2af4ebce24c379b949de69d49e3ba97c7e9c9775dc74d18307afa8618b7/expiringdict-1.2.2.tar.gz", hash = "sha256:300fb92a7e98f15b05cf9a856c1415b3bc4f2e132be07daa326da6414c23ee09", size = 8137, upload-time = "2022-06-21T09:12:30.415Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/cb/84/a04c59324445f4bcc98dc05b39a1cd07c242dde643c1a3c21e4f7beaf2f2/expiringdict-1.2.2-py3-none-any.whl", hash = "sha256:09a5d20bc361163e6432a874edd3179676e935eb81b925eccef48d409a8a45e8", size = 8456, upload-time = "2022-06-21T09:12:28.652Z" }, -] - [[package]] name = "faiss-cpu" version = "1.12.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", version = "1.26.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "numpy", version = "2.3.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "numpy" }, { name = "packaging" }, ] sdist = { url = "https://files.pythonhosted.org/packages/7d/80/bb75a7ed6e824dea452a24d3434a72ed799324a688b10b047d441d270185/faiss_cpu-1.12.0.tar.gz", hash = "sha256:2f87cbcd603f3ed464ebceb857971fdebc318de938566c9ae2b82beda8e953c0", size = 69292, upload-time = "2025-08-13T06:07:26.553Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/87/ed/83fed257ea410c2e691374f04ac914d5f9414f04a9c7a266bdfbb999eb16/faiss_cpu-1.12.0-cp311-cp311-macosx_13_0_x86_64.whl", hash = "sha256:fbb63595c7ad43c0d9caaf4d554a38a30ea4edda5e7c3ed38845562776992ba9", size = 8006079, upload-time = "2025-08-13T06:05:48.932Z" }, - { url = "https://files.pythonhosted.org/packages/5b/07/80c248db87ef2e753ad390fca3b0d7dd6092079e904f35b248c7064e791e/faiss_cpu-1.12.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:83e74cbde6fa5caceec5bc103c82053d50fde163e3ceabaa58c91508e984142b", size = 3360138, upload-time = "2025-08-13T06:05:50.873Z" }, - { url = "https://files.pythonhosted.org/packages/b9/22/73bd9ed7b11cd14eb0da6e2f2eae763306abaad1b25a5808da8b1fc07665/faiss_cpu-1.12.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:6155a5138604b702a32f8f0a63948a539eb7468898554a9911f9ab8c899284fb", size = 3825466, upload-time = "2025-08-13T06:05:52.311Z" }, - { url = "https://files.pythonhosted.org/packages/9e/7f/e1a21337b3cba24b953c760696e3b188a533d724440e050fd60a3c1aa919/faiss_cpu-1.12.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1bf4b5f0e9b6bb5a566b1a31e84a93b283f26c2b0155fb2eb5970c32a540a906", size = 31425626, upload-time = "2025-08-13T06:05:54.155Z" }, - { url = "https://files.pythonhosted.org/packages/05/24/f352cf8400f414e6a31385ef12d43d11aac8beb11d573a2fd00ec44b8cb7/faiss_cpu-1.12.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:60a535b79d3d6225c7c21d7277fb0c6fde80c46a9c1e33632b1b293c1d177f30", size = 9751949, upload-time = "2025-08-13T06:05:56.369Z" }, - { url = "https://files.pythonhosted.org/packages/05/50/a122e3076d7fd95cbe9a0cdf0fc796836f1e4fd399b418c6ba8533c75770/faiss_cpu-1.12.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0d1b243468a24564f85a41166f2ca4c92f8f6755da096ffbdcf551675ca739c5", size = 24161021, upload-time = "2025-08-13T06:05:58.776Z" }, - { url = "https://files.pythonhosted.org/packages/72/9f/3344f6fe69f6fbfb19dec298b4dda3d47a87dc31e418911fdcc3a3ace013/faiss_cpu-1.12.0-cp311-cp311-win_amd64.whl", hash = "sha256:84510079a2efe954e6b89fe5e62f23a98c1ef999756565e056f95f835ff43c5e", size = 18169278, upload-time = "2025-08-13T06:06:01.44Z" }, - { url = "https://files.pythonhosted.org/packages/4c/b1/37d532292c1b3dab690636947a532d3797741b09f2dfb9cb558ffeaff34b/faiss_cpu-1.12.0-cp311-cp311-win_arm64.whl", hash = "sha256:2283f1014f7f86dd56b53bf0ea0d7f848eb4c9c6704b8f4f99a0af02e994e479", size = 8007093, upload-time = "2025-08-13T06:06:03.904Z" }, { url = "https://files.pythonhosted.org/packages/4a/58/602ed184d35742eb240cbfea237bd214f2ae7f01cb369c39f4dff392f7c9/faiss_cpu-1.12.0-cp312-cp312-macosx_13_0_x86_64.whl", hash = "sha256:9b54990fcbcf90e37393909d4033520237194263c93ab6dbfae0616ef9af242b", size = 8034413, upload-time = "2025-08-13T06:06:05.564Z" }, { url = "https://files.pythonhosted.org/packages/83/d5/f84c3d0e022cdeb73ff8406a6834a7698829fa242eb8590ddf8a0b09357f/faiss_cpu-1.12.0-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:a5f5bca7e1a3e0a98480d1e2748fc86d12c28d506173e460e6746886ff0e08de", size = 3362034, upload-time = "2025-08-13T06:06:07.091Z" }, { url = "https://files.pythonhosted.org/packages/19/89/a4ba4d285ea4f9b0824bf31ebded3171da08bfcf5376f4771cc5481f72cd/faiss_cpu-1.12.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:016e391f49933875b8d60d47f282f2e93d8ea9f9ffbda82467aa771b11a237db", size = 3834319, upload-time = "2025-08-13T06:06:08.86Z" }, @@ -428,23 +383,24 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/01/61/d4b89fec821f72385526e1b9d9a3a0385dda4a72b206d28049e2c7cd39b8/gitpython-3.1.45-py3-none-any.whl", hash = "sha256:8908cb2e02fb3b93b7eb0f2827125cb699869470432cc885f019b8fd0fccff77", size = 208168, upload-time = "2025-07-24T03:45:52.517Z" }, ] +[[package]] +name = "googleapis-common-protos" +version = "1.76.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "protobuf" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/62/b6/bc095b23a3e0d978e75c8c18cabe4c11f791837410670e4486f0d539bfba/googleapis_common_protos-1.76.0.tar.gz", hash = "sha256:71db0e44a1d4c2dd024ebad44ca67129cc1e2892e4861df466764749d5ef8642", size = 156250, upload-time = "2026-10-22T23:43:36.263Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/05/6d/78dc67a9e779e594b49bf62604034d3a6aa428a55afc729cafda4b7333e1/googleapis_common_protos-1.76.0-py3-none-any.whl", hash = "sha256:59e13344a9f3651aa201a03e2bee815a3bf43a4baf1f9ff8a9b62a840ce25fac", size = 307707, upload-time = "2026-10-22T23:43:10.445Z" }, +] + [[package]] name = "greenlet" version = "3.2.4" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/03/b8/704d753a5a45507a7aab61f18db9509302ed3d0a27ac7e0359ec2905b1a6/greenlet-3.2.4.tar.gz", hash = "sha256:0dca0d95ff849f9a364385f36ab49f50065d76964944638be9691e1832e9f86d", size = 188260, upload-time = "2025-08-07T13:24:33.51Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/a4/de/f28ced0a67749cac23fecb02b694f6473f47686dff6afaa211d186e2ef9c/greenlet-3.2.4-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:96378df1de302bc38e99c3a9aa311967b7dc80ced1dcc6f171e99842987882a2", size = 272305, upload-time = "2025-08-07T13:15:41.288Z" }, - { url = "https://files.pythonhosted.org/packages/09/16/2c3792cba130000bf2a31c5272999113f4764fd9d874fb257ff588ac779a/greenlet-3.2.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:1ee8fae0519a337f2329cb78bd7a8e128ec0f881073d43f023c7b8d4831d5246", size = 632472, upload-time = "2025-08-07T13:42:55.044Z" }, - { url = "https://files.pythonhosted.org/packages/ae/8f/95d48d7e3d433e6dae5b1682e4292242a53f22df82e6d3dda81b1701a960/greenlet-3.2.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:94abf90142c2a18151632371140b3dba4dee031633fe614cb592dbb6c9e17bc3", size = 644646, upload-time = "2025-08-07T13:45:26.523Z" }, - { url = "https://files.pythonhosted.org/packages/d5/5e/405965351aef8c76b8ef7ad370e5da58d57ef6068df197548b015464001a/greenlet-3.2.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:4d1378601b85e2e5171b99be8d2dc85f594c79967599328f95c1dc1a40f1c633", size = 640519, upload-time = "2025-08-07T13:53:13.928Z" }, - { url = "https://files.pythonhosted.org/packages/25/5d/382753b52006ce0218297ec1b628e048c4e64b155379331f25a7316eb749/greenlet-3.2.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0db5594dce18db94f7d1650d7489909b57afde4c580806b8d9203b6e79cdc079", size = 639707, upload-time = "2025-08-07T13:18:27.146Z" }, - { url = "https://files.pythonhosted.org/packages/1f/8e/abdd3f14d735b2929290a018ecf133c901be4874b858dd1c604b9319f064/greenlet-3.2.4-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:2523e5246274f54fdadbce8494458a2ebdcdbc7b802318466ac5606d3cded1f8", size = 587684, upload-time = "2025-08-07T13:18:25.164Z" }, - { url = "https://files.pythonhosted.org/packages/5d/65/deb2a69c3e5996439b0176f6651e0052542bb6c8f8ec2e3fba97c9768805/greenlet-3.2.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:1987de92fec508535687fb807a5cea1560f6196285a4cde35c100b8cd632cc52", size = 1116647, upload-time = "2025-08-07T13:42:38.655Z" }, - { url = "https://files.pythonhosted.org/packages/3f/cc/b07000438a29ac5cfb2194bfc128151d52f333cee74dd7dfe3fb733fc16c/greenlet-3.2.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:55e9c5affaa6775e2c6b67659f3a71684de4c549b3dd9afca3bc773533d284fa", size = 1142073, upload-time = "2025-08-07T13:18:21.737Z" }, - { url = "https://files.pythonhosted.org/packages/67/24/28a5b2fa42d12b3d7e5614145f0bd89714c34c08be6aabe39c14dd52db34/greenlet-3.2.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c9c6de1940a7d828635fbd254d69db79e54619f165ee7ce32fda763a9cb6a58c", size = 1548385, upload-time = "2025-11-04T12:42:11.067Z" }, - { url = "https://files.pythonhosted.org/packages/6a/05/03f2f0bdd0b0ff9a4f7b99333d57b53a7709c27723ec8123056b084e69cd/greenlet-3.2.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:03c5136e7be905045160b1b9fdca93dd6727b180feeafda6818e6496434ed8c5", size = 1613329, upload-time = "2025-11-04T12:42:12.928Z" }, - { url = "https://files.pythonhosted.org/packages/d8/0f/30aef242fcab550b0b3520b8e3561156857c94288f0332a79928c31a52cf/greenlet-3.2.4-cp311-cp311-win_amd64.whl", hash = "sha256:9c40adce87eaa9ddb593ccb0fa6a07caf34015a29bf8d344811665b573138db9", size = 299100, upload-time = "2025-08-07T13:44:12.287Z" }, { url = "https://files.pythonhosted.org/packages/44/69/9b804adb5fd0671f367781560eb5eb586c4d495277c93bde4307b9e28068/greenlet-3.2.4-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:3b67ca49f54cede0186854a008109d6ee71f66bd57bb36abd6d0a0267b540cdd", size = 274079, upload-time = "2025-08-07T13:15:45.033Z" }, { url = "https://files.pythonhosted.org/packages/46/e9/d2a80c99f19a153eff70bc451ab78615583b8dac0754cfb942223d2c1a0d/greenlet-3.2.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ddf9164e7a5b08e9d22511526865780a576f19ddd00d62f8a665949327fde8bb", size = 640997, upload-time = "2025-08-07T13:42:56.234Z" }, { url = "https://files.pythonhosted.org/packages/3b/16/035dcfcc48715ccd345f3a93183267167cdd162ad123cd93067d86f27ce4/greenlet-3.2.4-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:f28588772bb5fb869a8eb331374ec06f24a83a9c25bfa1f38b6993afe9c1e968", size = 655185, upload-time = "2025-08-07T13:45:27.624Z" }, @@ -521,13 +477,6 @@ version = "0.6.4" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/a7/9a/ce5e1f7e131522e6d3426e8e7a490b3a01f39a6696602e1c4f33f9e94277/httptools-0.6.4.tar.gz", hash = "sha256:4e93eee4add6493b59a5c514da98c939b244fce4a0d8879cd3f466562f4b7d5c", size = 240639, upload-time = "2024-10-16T19:45:08.902Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7b/26/bb526d4d14c2774fe07113ca1db7255737ffbb119315839af2065abfdac3/httptools-0.6.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:f47f8ed67cc0ff862b84a1189831d1d33c963fb3ce1ee0c65d3b0cbe7b711069", size = 199029, upload-time = "2024-10-16T19:44:18.427Z" }, - { url = "https://files.pythonhosted.org/packages/a6/17/3e0d3e9b901c732987a45f4f94d4e2c62b89a041d93db89eafb262afd8d5/httptools-0.6.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:0614154d5454c21b6410fdf5262b4a3ddb0f53f1e1721cfd59d55f32138c578a", size = 103492, upload-time = "2024-10-16T19:44:19.515Z" }, - { url = "https://files.pythonhosted.org/packages/b7/24/0fe235d7b69c42423c7698d086d4db96475f9b50b6ad26a718ef27a0bce6/httptools-0.6.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f8787367fbdfccae38e35abf7641dafc5310310a5987b689f4c32cc8cc3ee975", size = 462891, upload-time = "2024-10-16T19:44:21.067Z" }, - { url = "https://files.pythonhosted.org/packages/b1/2f/205d1f2a190b72da6ffb5f41a3736c26d6fa7871101212b15e9b5cd8f61d/httptools-0.6.4-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40b0f7fe4fd38e6a507bdb751db0379df1e99120c65fbdc8ee6c1d044897a636", size = 459788, upload-time = "2024-10-16T19:44:22.958Z" }, - { url = "https://files.pythonhosted.org/packages/6e/4c/d09ce0eff09057a206a74575ae8f1e1e2f0364d20e2442224f9e6612c8b9/httptools-0.6.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:40a5ec98d3f49904b9fe36827dcf1aadfef3b89e2bd05b0e35e94f97c2b14721", size = 433214, upload-time = "2024-10-16T19:44:24.513Z" }, - { url = "https://files.pythonhosted.org/packages/3e/d2/84c9e23edbccc4a4c6f96a1b8d99dfd2350289e94f00e9ccc7aadde26fb5/httptools-0.6.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:dacdd3d10ea1b4ca9df97a0a303cbacafc04b5cd375fa98732678151643d4988", size = 434120, upload-time = "2024-10-16T19:44:26.295Z" }, - { url = "https://files.pythonhosted.org/packages/d0/46/4d8e7ba9581416de1c425b8264e2cadd201eb709ec1584c381f3e98f51c1/httptools-0.6.4-cp311-cp311-win_amd64.whl", hash = "sha256:288cd628406cc53f9a541cfaf06041b4c71d751856bab45e3702191f931ccd17", size = 88565, upload-time = "2024-10-16T19:44:29.188Z" }, { url = "https://files.pythonhosted.org/packages/bb/0e/d0b71465c66b9185f90a091ab36389a7352985fe857e352801c39d6127c8/httptools-0.6.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:df017d6c780287d5c80601dafa31f17bddb170232d85c066604d8558683711a2", size = 200683, upload-time = "2024-10-16T19:44:30.175Z" }, { url = "https://files.pythonhosted.org/packages/e2/b8/412a9bb28d0a8988de3296e01efa0bd62068b33856cdda47fe1b5e890954/httptools-0.6.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:85071a1e8c2d051b507161f6c3e26155b5c790e4e28d7f236422dbacc2a9cc44", size = 104337, upload-time = "2024-10-16T19:44:31.786Z" }, { url = "https://files.pythonhosted.org/packages/9b/01/6fb20be3196ffdc8eeec4e653bc2a275eca7f36634c86302242c4fbb2760/httptools-0.6.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:69422b7f458c5af875922cdb5bd586cc1f1033295aa9ff63ee196a87519ac8e1", size = 508796, upload-time = "2024-10-16T19:44:32.825Z" }, @@ -623,18 +572,6 @@ version = "0.10.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/ee/9d/ae7ddb4b8ab3fb1b51faf4deb36cb48a4fbbd7cb36bad6a5fca4741306f7/jiter-0.10.0.tar.gz", hash = "sha256:07a7142c38aacc85194391108dc91b5b57093c978a9932bd86a36862759d9500", size = 162759, upload-time = "2025-05-18T19:04:59.73Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/1b/dd/6cefc6bd68b1c3c979cecfa7029ab582b57690a31cd2f346c4d0ce7951b6/jiter-0.10.0-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:3bebe0c558e19902c96e99217e0b8e8b17d570906e72ed8a87170bc290b1e978", size = 317473, upload-time = "2025-05-18T19:03:25.942Z" }, - { url = "https://files.pythonhosted.org/packages/be/cf/fc33f5159ce132be1d8dd57251a1ec7a631c7df4bd11e1cd198308c6ae32/jiter-0.10.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:558cc7e44fd8e507a236bee6a02fa17199ba752874400a0ca6cd6e2196cdb7dc", size = 321971, upload-time = "2025-05-18T19:03:27.255Z" }, - { url = "https://files.pythonhosted.org/packages/68/a4/da3f150cf1d51f6c472616fb7650429c7ce053e0c962b41b68557fdf6379/jiter-0.10.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4d613e4b379a07d7c8453c5712ce7014e86c6ac93d990a0b8e7377e18505e98d", size = 345574, upload-time = "2025-05-18T19:03:28.63Z" }, - { url = "https://files.pythonhosted.org/packages/84/34/6e8d412e60ff06b186040e77da5f83bc158e9735759fcae65b37d681f28b/jiter-0.10.0-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f62cf8ba0618eda841b9bf61797f21c5ebd15a7a1e19daab76e4e4b498d515b2", size = 371028, upload-time = "2025-05-18T19:03:30.292Z" }, - { url = "https://files.pythonhosted.org/packages/fb/d9/9ee86173aae4576c35a2f50ae930d2ccb4c4c236f6cb9353267aa1d626b7/jiter-0.10.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:919d139cdfa8ae8945112398511cb7fca58a77382617d279556b344867a37e61", size = 491083, upload-time = "2025-05-18T19:03:31.654Z" }, - { url = "https://files.pythonhosted.org/packages/d9/2c/f955de55e74771493ac9e188b0f731524c6a995dffdcb8c255b89c6fb74b/jiter-0.10.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:13ddbc6ae311175a3b03bd8994881bc4635c923754932918e18da841632349db", size = 388821, upload-time = "2025-05-18T19:03:33.184Z" }, - { url = "https://files.pythonhosted.org/packages/81/5a/0e73541b6edd3f4aada586c24e50626c7815c561a7ba337d6a7eb0a915b4/jiter-0.10.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4c440ea003ad10927a30521a9062ce10b5479592e8a70da27f21eeb457b4a9c5", size = 352174, upload-time = "2025-05-18T19:03:34.965Z" }, - { url = "https://files.pythonhosted.org/packages/1c/c0/61eeec33b8c75b31cae42be14d44f9e6fe3ac15a4e58010256ac3abf3638/jiter-0.10.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:dc347c87944983481e138dea467c0551080c86b9d21de6ea9306efb12ca8f606", size = 391869, upload-time = "2025-05-18T19:03:36.436Z" }, - { url = "https://files.pythonhosted.org/packages/41/22/5beb5ee4ad4ef7d86f5ea5b4509f680a20706c4a7659e74344777efb7739/jiter-0.10.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:13252b58c1f4d8c5b63ab103c03d909e8e1e7842d302473f482915d95fefd605", size = 523741, upload-time = "2025-05-18T19:03:38.168Z" }, - { url = "https://files.pythonhosted.org/packages/ea/10/768e8818538e5817c637b0df52e54366ec4cebc3346108a4457ea7a98f32/jiter-0.10.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:7d1bbf3c465de4a24ab12fb7766a0003f6f9bce48b8b6a886158c4d569452dc5", size = 514527, upload-time = "2025-05-18T19:03:39.577Z" }, - { url = "https://files.pythonhosted.org/packages/73/6d/29b7c2dc76ce93cbedabfd842fc9096d01a0550c52692dfc33d3cc889815/jiter-0.10.0-cp311-cp311-win32.whl", hash = "sha256:db16e4848b7e826edca4ccdd5b145939758dadf0dc06e7007ad0e9cfb5928ae7", size = 210765, upload-time = "2025-05-18T19:03:41.271Z" }, - { url = "https://files.pythonhosted.org/packages/c2/c9/d394706deb4c660137caf13e33d05a031d734eb99c051142e039d8ceb794/jiter-0.10.0-cp311-cp311-win_amd64.whl", hash = "sha256:9c9c1d5f10e18909e993f9641f12fe1c77b3e9b533ee94ffa970acc14ded3812", size = 209234, upload-time = "2025-05-18T19:03:42.918Z" }, { url = "https://files.pythonhosted.org/packages/6d/b5/348b3313c58f5fbfb2194eb4d07e46a35748ba6e5b3b3046143f3040bafa/jiter-0.10.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:1e274728e4a5345a6dde2d343c8da018b9d4bd4350f5a472fa91f66fda44911b", size = 312262, upload-time = "2025-05-18T19:03:44.637Z" }, { url = "https://files.pythonhosted.org/packages/9c/4a/6a2397096162b21645162825f058d1709a02965606e537e3304b02742e9b/jiter-0.10.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7202ae396446c988cb2a5feb33a543ab2165b786ac97f53b59aafb803fef0744", size = 320124, upload-time = "2025-05-18T19:03:46.341Z" }, { url = "https://files.pythonhosted.org/packages/2a/85/1ce02cade7516b726dd88f59a4ee46914bf79d1676d1228ef2002ed2f1c9/jiter-0.10.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:23ba7722d6748b6920ed02a8f1726fb4b33e0fd2f3f621816a8b486c66410ab2", size = 345330, upload-time = "2025-05-18T19:03:47.596Z" }, @@ -773,8 +710,7 @@ source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "boto3" }, { name = "langchain-core" }, - { name = "numpy", version = "1.26.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "numpy", version = "2.3.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "numpy" }, { name = "pydantic" }, ] sdist = { url = "https://files.pythonhosted.org/packages/8d/7a/19a903725acbb1c4481dc0391b2551250bf4e04cbe5a891a55e09319772b/langchain_aws-0.2.35.tar.gz", hash = "sha256:45793a34fe45d365f4292cc768db74669ca24601d2c5da1ac6f44403750d70af", size = 120567, upload-time = "2025-10-02T23:59:57.204Z" } @@ -931,45 +867,49 @@ wheels = [ ] [[package]] -name = "launchdarkly-eventsource" -version = "1.3.0" +name = "launchdarkly-ai-server" +version = "1.1.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "urllib3" }, + { name = "opentelemetry-api" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/8f/23/e5f6afff983e2c03767617291fda895af2849f3176ea78aa106baade70dc/launchdarkly_eventsource-1.3.0.tar.gz", hash = "sha256:5029199b2c344aee2806bbe8784965e9c0197d052d0bab7e1396a94c159f6bc8", size = 22343, upload-time = "2025-06-26T17:21:29.154Z" } +sdist = { url = "https://files.pythonhosted.org/packages/bc/de/5ac3b740979de7b65d9f1f66eb5ac36a705617da50e45e9bc40e4fa2cee5/launchdarkly_ai_server-1.1.0.tar.gz", hash = "sha256:579c5fefba26c4469fce5085d956bfd95f9665c89fe011b1062cd4439652c1dd", size = 527963, upload-time = "2026-11-12T20:32:30.265Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/4e/95/c20ba9cd28951f360b222da09138daf9169ad951be2a0d500eb0f0c84614/launchdarkly_eventsource-1.3.0-py3-none-any.whl", hash = "sha256:7afecee7a0f306630e4364994e0816abbbdbaf143fe43b3428ed122fa4e0d487", size = 29471, upload-time = "2025-06-26T17:21:28.025Z" }, + { url = "https://files.pythonhosted.org/packages/5f/59/5a633e57fcb379a853d8d827acf9023699ff0d6501ef587df994879db456/launchdarkly_ai_server-1.1.0-py3-none-any.whl", hash = "sha256:c905b992dca4d1b28be594ae19f166a87c13b9d5fb68381227d47110dacc713f", size = 232643, upload-time = "2026-11-12T20:32:29.111Z" }, +] + +[package.optional-dependencies] +otel = [ + { name = "opentelemetry-exporter-otlp-proto-http" }, + { name = "opentelemetry-sdk" }, ] [[package]] -name = "launchdarkly-server-sdk" -version = "9.12.0" +name = "launchdarkly-eventsource" +version = "1.7.4" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "certifi" }, - { name = "expiringdict" }, - { name = "launchdarkly-eventsource" }, - { name = "pyrfc3339" }, - { name = "semver" }, { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/19/27/ae186fca5498dbcd80e93940716997a83c09b401b3ee0889dcbb5e3dcd2e/launchdarkly_server_sdk-9.12.0.tar.gz", hash = "sha256:219b100d7569e4f528b6028cbd2a5d61f13539f2b44ed43fc173bb4f456ee580", size = 165130, upload-time = "2025-07-14T16:04:29.253Z" } +sdist = { url = "https://files.pythonhosted.org/packages/ac/6c/60862f8143c8185e953410b30125ff37ce4720fac2042771ca00f115f840/launchdarkly_eventsource-1.7.4.tar.gz", hash = "sha256:0a608da152a53bd05f5b4a2486828f21d48cd25a56986e36a8e47a8e9975e309", size = 46060, upload-time = "2026-10-19T15:27:17.989Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/72/45/ff696e71a724e4ed686bbf5e57537c08baabde900e229d2a167040aa5e40/launchdarkly_server_sdk-9.12.0-py3-none-any.whl", hash = "sha256:c7351e26e6b695b968d49888e967691aae60ded82d73a41a74d59d11252a1413", size = 219654, upload-time = "2025-07-14T16:04:27.866Z" }, + { url = "https://files.pythonhosted.org/packages/8c/e3/6dae165ff56bba3ad4fc76b2aa8c4606c577d2e33a9053dc147b03b045b6/launchdarkly_eventsource-1.7.4-py3-none-any.whl", hash = "sha256:42bbaee1741675199be193d99229ecb710a94089e74fc68b8c4edb90cddbdc5e", size = 29560, upload-time = "2026-10-19T15:27:16.988Z" }, ] [[package]] -name = "launchdarkly-server-sdk-ai" -version = "0.20.1" +name = "launchdarkly-server-sdk" +version = "9.21.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "chevron" }, - { name = "launchdarkly-server-sdk" }, + { name = "certifi" }, + { name = "launchdarkly-eventsource" }, + { name = "pyrfc3339" }, + { name = "semver" }, + { name = "urllib3" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/93/d8/b63c57ebfecf41694926270b1cc36b5d2d08f96a65029e3179ea15fad45a/launchdarkly_server_sdk_ai-0.20.1.tar.gz", hash = "sha256:f6fe18ba83192542c574ebc9c994644ca2977f94331e3de09d33a14a46d5944e", size = 89689, upload-time = "2026-05-14T22:43:01.731Z" } +sdist = { url = "https://files.pythonhosted.org/packages/d6/63/d71b230ed98354523c3bba9950b1498a74c1824c39f425400a0cd27b8841/launchdarkly_server_sdk-9.21.0.tar.gz", hash = "sha256:c1db1ebcc5045b3785bd169e780f521a625f5201382dca7cbe85fd871a4103c8", size = 518639, upload-time = "2026-11-12T21:45:44.315Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0d/3b/4166156f0b699f5877a28c2eea2908c7ce8c89d17fd193735250e2501272/launchdarkly_server_sdk_ai-0.20.1-py3-none-any.whl", hash = "sha256:54048f2b96a2f264e0a826b281af8de5a94e729cfce455db87d00ac164d77831", size = 37391, upload-time = "2026-05-14T22:43:00.275Z" }, + { url = "https://files.pythonhosted.org/packages/57/df/9c22e54b59b1c64bd5b4a5880d4f00aa92448fc0da16493e86090470739e/launchdarkly_server_sdk-9.21.0-py3-none-any.whl", hash = "sha256:ce87d00caa655c5ebb9a2656e65432c64c47529f5df588513043fe9d4fd46afe", size = 324888, upload-time = "2026-11-12T21:45:43.152Z" }, ] [[package]] @@ -978,16 +918,6 @@ version = "3.0.2" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/b2/97/5d42485e71dfc078108a86d6de8fa46db44a1a9295e89c5d6d4a06e23a62/markupsafe-3.0.2.tar.gz", hash = "sha256:ee55d3edf80167e48ea11a923c7386f4669df67d7994554387f84e7d8b0a2bf0", size = 20537, upload-time = "2024-10-18T15:21:54.129Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/6b/28/bbf83e3f76936960b850435576dd5e67034e200469571be53f69174a2dfd/MarkupSafe-3.0.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9025b4018f3a1314059769c7bf15441064b2207cb3f065e6ea1e7359cb46db9d", size = 14353, upload-time = "2024-10-18T15:21:02.187Z" }, - { url = "https://files.pythonhosted.org/packages/6c/30/316d194b093cde57d448a4c3209f22e3046c5bb2fb0820b118292b334be7/MarkupSafe-3.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:93335ca3812df2f366e80509ae119189886b0f3c2b81325d39efdb84a1e2ae93", size = 12392, upload-time = "2024-10-18T15:21:02.941Z" }, - { url = "https://files.pythonhosted.org/packages/f2/96/9cdafba8445d3a53cae530aaf83c38ec64c4d5427d975c974084af5bc5d2/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2cb8438c3cbb25e220c2ab33bb226559e7afb3baec11c4f218ffa7308603c832", size = 23984, upload-time = "2024-10-18T15:21:03.953Z" }, - { url = "https://files.pythonhosted.org/packages/f1/a4/aefb044a2cd8d7334c8a47d3fb2c9f328ac48cb349468cc31c20b539305f/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a123e330ef0853c6e822384873bef7507557d8e4a082961e1defa947aa59ba84", size = 23120, upload-time = "2024-10-18T15:21:06.495Z" }, - { url = "https://files.pythonhosted.org/packages/8d/21/5e4851379f88f3fad1de30361db501300d4f07bcad047d3cb0449fc51f8c/MarkupSafe-3.0.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1e084f686b92e5b83186b07e8a17fc09e38fff551f3602b249881fec658d3eca", size = 23032, upload-time = "2024-10-18T15:21:07.295Z" }, - { url = "https://files.pythonhosted.org/packages/00/7b/e92c64e079b2d0d7ddf69899c98842f3f9a60a1ae72657c89ce2655c999d/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:d8213e09c917a951de9d09ecee036d5c7d36cb6cb7dbaece4c71a60d79fb9798", size = 24057, upload-time = "2024-10-18T15:21:08.073Z" }, - { url = "https://files.pythonhosted.org/packages/f9/ac/46f960ca323037caa0a10662ef97d0a4728e890334fc156b9f9e52bcc4ca/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:5b02fb34468b6aaa40dfc198d813a641e3a63b98c2b05a16b9f80b7ec314185e", size = 23359, upload-time = "2024-10-18T15:21:09.318Z" }, - { url = "https://files.pythonhosted.org/packages/69/84/83439e16197337b8b14b6a5b9c2105fff81d42c2a7c5b58ac7b62ee2c3b1/MarkupSafe-3.0.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0bff5e0ae4ef2e1ae4fdf2dfd5b76c75e5c2fa4132d05fc1b0dabcd20c7e28c4", size = 23306, upload-time = "2024-10-18T15:21:10.185Z" }, - { url = "https://files.pythonhosted.org/packages/9a/34/a15aa69f01e2181ed8d2b685c0d2f6655d5cca2c4db0ddea775e631918cd/MarkupSafe-3.0.2-cp311-cp311-win32.whl", hash = "sha256:6c89876f41da747c8d3677a2b540fb32ef5715f97b66eeb0c6b66f5e3ef6f59d", size = 15094, upload-time = "2024-10-18T15:21:11.005Z" }, - { url = "https://files.pythonhosted.org/packages/da/b8/3a3bd761922d416f3dc5d00bfbed11f66b1ab89a0c2b6e887240a30b0f6b/MarkupSafe-3.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:70a87b411535ccad5ef2f1df5136506a10775d267e197e4cf531ced10537bd6b", size = 15521, upload-time = "2024-10-18T15:21:12.911Z" }, { url = "https://files.pythonhosted.org/packages/22/09/d1f21434c97fc42f09d290cbb6350d44eb12f09cc62c9476effdb33a18aa/MarkupSafe-3.0.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:9778bd8ab0a994ebf6f84c2b949e65736d5575320a17ae8984a77fab08db94cf", size = 14274, upload-time = "2024-10-18T15:21:13.777Z" }, { url = "https://files.pythonhosted.org/packages/6b/b0/18f76bba336fa5aecf79d45dcd6c806c280ec44538b3c13671d49099fdd0/MarkupSafe-3.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:846ade7b71e3536c4e56b386c2a47adf5741d2d8b94ec9dc3e92e5e1ee1e2225", size = 12348, upload-time = "2024-10-18T15:21:14.822Z" }, { url = "https://files.pythonhosted.org/packages/e0/25/dd5c0f6ac1311e9b40f4af06c78efde0f3b5cbf02502f8ef9501294c425b/MarkupSafe-3.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1c99d261bd2d5f6b59325c92c73df481e05e57f19837bdca8413b9eac4bd8028", size = 24149, upload-time = "2024-10-18T15:21:15.642Z" }, @@ -1051,62 +981,12 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/dd/54/1ecca75e51d7da8ca53d1ffa8636ef9077a6eaa31f43ade71360b3e6449a/narwhals-2.2.0-py3-none-any.whl", hash = "sha256:2b5e3d61a486fa4328c286b0c8018b3e781a964947ff725d66ba12f6d5ca3d2a", size = 401021, upload-time = "2025-08-25T07:51:56.97Z" }, ] -[[package]] -name = "nest-asyncio" -version = "1.6.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/83/f8/51569ac65d696c8ecbee95938f89d4abf00f47d58d48f6fbabfe8f0baefe/nest_asyncio-1.6.0.tar.gz", hash = "sha256:6f172d5449aca15afd6c646851f4e31e02c598d553a667e38cafa997cfec55fe", size = 7418, upload-time = "2024-01-21T14:25:19.227Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/a0/c4/c2971a3ba4c6103a3d10c4b0f24f461ddc027f0f09763220cf35ca1401b3/nest_asyncio-1.6.0-py3-none-any.whl", hash = "sha256:87af6efd6b5e897c81050477ef65c62e2b2f35d51703cae01aff2905b1852e1c", size = 5195, upload-time = "2024-01-21T14:25:17.223Z" }, -] - -[[package]] -name = "numpy" -version = "1.26.4" -source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version < '3.12'", -] -sdist = { url = "https://files.pythonhosted.org/packages/65/6e/09db70a523a96d25e115e71cc56a6f9031e7b8cd166c1ac8438307c14058/numpy-1.26.4.tar.gz", hash = "sha256:2a02aba9ed12e4ac4eb3ea9421c420301a0c6460d9830d74a9df87efa4912010", size = 15786129, upload-time = "2024-02-06T00:26:44.495Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/11/57/baae43d14fe163fa0e4c47f307b6b2511ab8d7d30177c491960504252053/numpy-1.26.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4c66707fabe114439db9068ee468c26bbdf909cac0fb58686a42a24de1760c71", size = 20630554, upload-time = "2024-02-05T23:51:50.149Z" }, - { url = "https://files.pythonhosted.org/packages/1a/2e/151484f49fd03944c4a3ad9c418ed193cfd02724e138ac8a9505d056c582/numpy-1.26.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:edd8b5fe47dab091176d21bb6de568acdd906d1887a4584a15a9a96a1dca06ef", size = 13997127, upload-time = "2024-02-05T23:52:15.314Z" }, - { url = "https://files.pythonhosted.org/packages/79/ae/7e5b85136806f9dadf4878bf73cf223fe5c2636818ba3ab1c585d0403164/numpy-1.26.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7ab55401287bfec946ced39700c053796e7cc0e3acbef09993a9ad2adba6ca6e", size = 14222994, upload-time = "2024-02-05T23:52:47.569Z" }, - { url = "https://files.pythonhosted.org/packages/3a/d0/edc009c27b406c4f9cbc79274d6e46d634d139075492ad055e3d68445925/numpy-1.26.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:666dbfb6ec68962c033a450943ded891bed2d54e6755e35e5835d63f4f6931d5", size = 18252005, upload-time = "2024-02-05T23:53:15.637Z" }, - { url = "https://files.pythonhosted.org/packages/09/bf/2b1aaf8f525f2923ff6cfcf134ae5e750e279ac65ebf386c75a0cf6da06a/numpy-1.26.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:96ff0b2ad353d8f990b63294c8986f1ec3cb19d749234014f4e7eb0112ceba5a", size = 13885297, upload-time = "2024-02-05T23:53:42.16Z" }, - { url = "https://files.pythonhosted.org/packages/df/a0/4e0f14d847cfc2a633a1c8621d00724f3206cfeddeb66d35698c4e2cf3d2/numpy-1.26.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:60dedbb91afcbfdc9bc0b1f3f402804070deed7392c23eb7a7f07fa857868e8a", size = 18093567, upload-time = "2024-02-05T23:54:11.696Z" }, - { url = "https://files.pythonhosted.org/packages/d2/b7/a734c733286e10a7f1a8ad1ae8c90f2d33bf604a96548e0a4a3a6739b468/numpy-1.26.4-cp311-cp311-win32.whl", hash = "sha256:1af303d6b2210eb850fcf03064d364652b7120803a0b872f5211f5234b399f20", size = 5968812, upload-time = "2024-02-05T23:54:26.453Z" }, - { url = "https://files.pythonhosted.org/packages/3f/6b/5610004206cf7f8e7ad91c5a85a8c71b2f2f8051a0c0c4d5916b76d6cbb2/numpy-1.26.4-cp311-cp311-win_amd64.whl", hash = "sha256:cd25bcecc4974d09257ffcd1f098ee778f7834c3ad767fe5db785be9a4aa9cb2", size = 15811913, upload-time = "2024-02-05T23:54:53.933Z" }, - { url = "https://files.pythonhosted.org/packages/95/12/8f2020a8e8b8383ac0177dc9570aad031a3beb12e38847f7129bacd96228/numpy-1.26.4-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:b3ce300f3644fb06443ee2222c2201dd3a89ea6040541412b8fa189341847218", size = 20335901, upload-time = "2024-02-05T23:55:32.801Z" }, - { url = "https://files.pythonhosted.org/packages/75/5b/ca6c8bd14007e5ca171c7c03102d17b4f4e0ceb53957e8c44343a9546dcc/numpy-1.26.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:03a8c78d01d9781b28a6989f6fa1bb2c4f2d51201cf99d3dd875df6fbd96b23b", size = 13685868, upload-time = "2024-02-05T23:55:56.28Z" }, - { url = "https://files.pythonhosted.org/packages/79/f8/97f10e6755e2a7d027ca783f63044d5b1bc1ae7acb12afe6a9b4286eac17/numpy-1.26.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9fad7dcb1aac3c7f0584a5a8133e3a43eeb2fe127f47e3632d43d677c66c102b", size = 13925109, upload-time = "2024-02-05T23:56:20.368Z" }, - { url = "https://files.pythonhosted.org/packages/0f/50/de23fde84e45f5c4fda2488c759b69990fd4512387a8632860f3ac9cd225/numpy-1.26.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:675d61ffbfa78604709862923189bad94014bef562cc35cf61d3a07bba02a7ed", size = 17950613, upload-time = "2024-02-05T23:56:56.054Z" }, - { url = "https://files.pythonhosted.org/packages/4c/0c/9c603826b6465e82591e05ca230dfc13376da512b25ccd0894709b054ed0/numpy-1.26.4-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:ab47dbe5cc8210f55aa58e4805fe224dac469cde56b9f731a4c098b91917159a", size = 13572172, upload-time = "2024-02-05T23:57:21.56Z" }, - { url = "https://files.pythonhosted.org/packages/76/8c/2ba3902e1a0fc1c74962ea9bb33a534bb05984ad7ff9515bf8d07527cadd/numpy-1.26.4-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:1dda2e7b4ec9dd512f84935c5f126c8bd8b9f2fc001e9f54af255e8c5f16b0e0", size = 17786643, upload-time = "2024-02-05T23:57:56.585Z" }, - { url = "https://files.pythonhosted.org/packages/28/4a/46d9e65106879492374999e76eb85f87b15328e06bd1550668f79f7b18c6/numpy-1.26.4-cp312-cp312-win32.whl", hash = "sha256:50193e430acfc1346175fcbdaa28ffec49947a06918b7b92130744e81e640110", size = 5677803, upload-time = "2024-02-05T23:58:08.963Z" }, - { url = "https://files.pythonhosted.org/packages/16/2e/86f24451c2d530c88daf997cb8d6ac622c1d40d19f5a031ed68a4b73a374/numpy-1.26.4-cp312-cp312-win_amd64.whl", hash = "sha256:08beddf13648eb95f8d867350f6a018a4be2e5ad54c8d8caed89ebca558b2818", size = 15517754, upload-time = "2024-02-05T23:58:36.364Z" }, -] - [[package]] name = "numpy" version = "2.3.2" source = { registry = "https://pypi.org/simple" } -resolution-markers = [ - "python_full_version >= '3.12'", -] sdist = { url = "https://files.pythonhosted.org/packages/37/7d/3fec4199c5ffb892bed55cff901e4f39a58c81df9c44c280499e92cad264/numpy-2.3.2.tar.gz", hash = "sha256:e0486a11ec30cdecb53f184d496d1c6a20786c81e55e41640270130056f8ee48", size = 20489306, upload-time = "2025-07-24T21:32:07.553Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/96/26/1320083986108998bd487e2931eed2aeedf914b6e8905431487543ec911d/numpy-2.3.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:852ae5bed3478b92f093e30f785c98e0cb62fa0a939ed057c31716e18a7a22b9", size = 21259016, upload-time = "2025-07-24T20:24:35.214Z" }, - { url = "https://files.pythonhosted.org/packages/c4/2b/792b341463fa93fc7e55abbdbe87dac316c5b8cb5e94fb7a59fb6fa0cda5/numpy-2.3.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7a0e27186e781a69959d0230dd9909b5e26024f8da10683bd6344baea1885168", size = 14451158, upload-time = "2025-07-24T20:24:58.397Z" }, - { url = "https://files.pythonhosted.org/packages/b7/13/e792d7209261afb0c9f4759ffef6135b35c77c6349a151f488f531d13595/numpy-2.3.2-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:f0a1a8476ad77a228e41619af2fa9505cf69df928e9aaa165746584ea17fed2b", size = 5379817, upload-time = "2025-07-24T20:25:07.746Z" }, - { url = "https://files.pythonhosted.org/packages/49/ce/055274fcba4107c022b2113a213c7287346563f48d62e8d2a5176ad93217/numpy-2.3.2-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:cbc95b3813920145032412f7e33d12080f11dc776262df1712e1638207dde9e8", size = 6913606, upload-time = "2025-07-24T20:25:18.84Z" }, - { url = "https://files.pythonhosted.org/packages/17/f2/e4d72e6bc5ff01e2ab613dc198d560714971900c03674b41947e38606502/numpy-2.3.2-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f75018be4980a7324edc5930fe39aa391d5734531b1926968605416ff58c332d", size = 14589652, upload-time = "2025-07-24T20:25:40.356Z" }, - { url = "https://files.pythonhosted.org/packages/c8/b0/fbeee3000a51ebf7222016e2939b5c5ecf8000a19555d04a18f1e02521b8/numpy-2.3.2-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:20b8200721840f5621b7bd03f8dcd78de33ec522fc40dc2641aa09537df010c3", size = 16938816, upload-time = "2025-07-24T20:26:05.721Z" }, - { url = "https://files.pythonhosted.org/packages/a9/ec/2f6c45c3484cc159621ea8fc000ac5a86f1575f090cac78ac27193ce82cd/numpy-2.3.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1f91e5c028504660d606340a084db4b216567ded1056ea2b4be4f9d10b67197f", size = 16370512, upload-time = "2025-07-24T20:26:30.545Z" }, - { url = "https://files.pythonhosted.org/packages/b5/01/dd67cf511850bd7aefd6347aaae0956ed415abea741ae107834aae7d6d4e/numpy-2.3.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:fb1752a3bb9a3ad2d6b090b88a9a0ae1cd6f004ef95f75825e2f382c183b2097", size = 18884947, upload-time = "2025-07-24T20:26:58.24Z" }, - { url = "https://files.pythonhosted.org/packages/a7/17/2cf60fd3e6a61d006778735edf67a222787a8c1a7842aed43ef96d777446/numpy-2.3.2-cp311-cp311-win32.whl", hash = "sha256:4ae6863868aaee2f57503c7a5052b3a2807cf7a3914475e637a0ecd366ced220", size = 6599494, upload-time = "2025-07-24T20:27:09.786Z" }, - { url = "https://files.pythonhosted.org/packages/d5/03/0eade211c504bda872a594f045f98ddcc6caef2b7c63610946845e304d3f/numpy-2.3.2-cp311-cp311-win_amd64.whl", hash = "sha256:240259d6564f1c65424bcd10f435145a7644a65a6811cfc3201c4a429ba79170", size = 13087889, upload-time = "2025-07-24T20:27:29.558Z" }, - { url = "https://files.pythonhosted.org/packages/13/32/2c7979d39dafb2a25087e12310fc7f3b9d3c7d960df4f4bc97955ae0ce1d/numpy-2.3.2-cp311-cp311-win_arm64.whl", hash = "sha256:4209f874d45f921bde2cff1ffcd8a3695f545ad2ffbef6d3d3c6768162efab89", size = 10459560, upload-time = "2025-07-24T20:27:46.803Z" }, { url = "https://files.pythonhosted.org/packages/00/6d/745dd1c1c5c284d17725e5c802ca4d45cfc6803519d777f087b71c9f4069/numpy-2.3.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:bc3186bea41fae9d8e90c2b4fb5f0a1f5a690682da79b92574d63f56b529080b", size = 20956420, upload-time = "2025-07-24T20:28:18.002Z" }, { url = "https://files.pythonhosted.org/packages/bc/96/e7b533ea5740641dd62b07a790af5d9d8fec36000b8e2d0472bd7574105f/numpy-2.3.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:2f4f0215edb189048a3c03bd5b19345bdfa7b45a7a6f72ae5945d2a28272727f", size = 14184660, upload-time = "2025-07-24T20:28:39.522Z" }, { url = "https://files.pythonhosted.org/packages/2b/53/102c6122db45a62aa20d1b18c9986f67e6b97e0d6fbc1ae13e3e4c84430c/numpy-2.3.2-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:8b1224a734cd509f70816455c3cffe13a4f599b1bf7130f913ba0e2c0b2006c0", size = 5113382, upload-time = "2025-07-24T20:28:48.544Z" }, @@ -1162,13 +1042,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/14/ba/5b5c9978c4bb161034148ade2de9db44ec316fab89ce8c400db0e0c81f86/numpy-2.3.2-cp314-cp314t-win32.whl", hash = "sha256:6f1ae3dcb840edccc45af496f312528c15b1f79ac318169d094e85e4bb35fdf1", size = 6514777, upload-time = "2025-07-24T20:55:57.66Z" }, { url = "https://files.pythonhosted.org/packages/eb/46/3dbaf0ae7c17cdc46b9f662c56da2054887b8d9e737c1476f335c83d33db/numpy-2.3.2-cp314-cp314t-win_amd64.whl", hash = "sha256:087ffc25890d89a43536f75c5fe8770922008758e8eeeef61733957041ed2f9b", size = 13111856, upload-time = "2025-07-24T20:56:17.318Z" }, { url = "https://files.pythonhosted.org/packages/c1/9e/1652778bce745a67b5fe05adde60ed362d38eb17d919a540e813d30f6874/numpy-2.3.2-cp314-cp314t-win_arm64.whl", hash = "sha256:092aeb3449833ea9c0bf0089d70c29ae480685dd2377ec9cdbbb620257f84631", size = 10544226, upload-time = "2025-07-24T20:56:34.509Z" }, - { url = "https://files.pythonhosted.org/packages/cf/ea/50ebc91d28b275b23b7128ef25c3d08152bc4068f42742867e07a870a42a/numpy-2.3.2-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:14a91ebac98813a49bc6aa1a0dfc09513dcec1d97eaf31ca21a87221a1cdcb15", size = 21130338, upload-time = "2025-07-24T20:57:54.37Z" }, - { url = "https://files.pythonhosted.org/packages/9f/57/cdd5eac00dd5f137277355c318a955c0d8fb8aa486020c22afd305f8b88f/numpy-2.3.2-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:71669b5daae692189540cffc4c439468d35a3f84f0c88b078ecd94337f6cb0ec", size = 14375776, upload-time = "2025-07-24T20:58:16.303Z" }, - { url = "https://files.pythonhosted.org/packages/83/85/27280c7f34fcd305c2209c0cdca4d70775e4859a9eaa92f850087f8dea50/numpy-2.3.2-pp311-pypy311_pp73-macosx_14_0_arm64.whl", hash = "sha256:69779198d9caee6e547adb933941ed7520f896fd9656834c300bdf4dd8642712", size = 5304882, upload-time = "2025-07-24T20:58:26.199Z" }, - { url = "https://files.pythonhosted.org/packages/48/b4/6500b24d278e15dd796f43824e69939d00981d37d9779e32499e823aa0aa/numpy-2.3.2-pp311-pypy311_pp73-macosx_14_0_x86_64.whl", hash = "sha256:2c3271cc4097beb5a60f010bcc1cc204b300bb3eafb4399376418a83a1c6373c", size = 6818405, upload-time = "2025-07-24T20:58:37.341Z" }, - { url = "https://files.pythonhosted.org/packages/9b/c9/142c1e03f199d202da8e980c2496213509291b6024fd2735ad28ae7065c7/numpy-2.3.2-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8446acd11fe3dc1830568c941d44449fd5cb83068e5c70bd5a470d323d448296", size = 14419651, upload-time = "2025-07-24T20:58:59.048Z" }, - { url = "https://files.pythonhosted.org/packages/8b/95/8023e87cbea31a750a6c00ff9427d65ebc5fef104a136bfa69f76266d614/numpy-2.3.2-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:aa098a5ab53fa407fded5870865c6275a5cd4101cfdef8d6fafc48286a96e981", size = 16760166, upload-time = "2025-07-24T21:28:56.38Z" }, - { url = "https://files.pythonhosted.org/packages/78/e3/6690b3f85a05506733c7e90b577e4762517404ea78bab2ca3a5cb1aeb78d/numpy-2.3.2-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:6936aff90dda378c09bea075af0d9c675fe3a977a9d2402f95a87f440f59f619", size = 12977811, upload-time = "2025-07-24T21:29:18.234Z" }, ] [[package]] @@ -1190,27 +1063,124 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c8/a6/0e39baa335bbd1c66c7e0a41dbbec10c5a15ab95c1344e7f7beb28eee65a/openai-1.101.0-py3-none-any.whl", hash = "sha256:6539a446cce154f8d9fb42757acdfd3ed9357ab0d34fcac11096c461da87133b", size = 810772, upload-time = "2025-08-21T21:10:59.215Z" }, ] +[[package]] +name = "opentelemetry-api" +version = "1.45.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/14/cf3a6b6448849656e1e5f4e2101f3988dc6789724050096aba1bc5ccf592/opentelemetry_api-1.45.2.tar.gz", hash = "sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4", size = 73277, upload-time = "2026-10-29T17:29:37.888Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/2d/610db864d7513158cebb8f36cc88e67e73bd6c7aa1905ef18d89e1281c81/opentelemetry_api-1.45.2-py3-none-any.whl", hash = "sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34", size = 60335, upload-time = "2026-10-29T17:29:06.955Z" }, +] + +[[package]] +name = "opentelemetry-exporter-http-transport" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a6/e6/dbeb3e217418071656232a4028c791060d219f218cef1249b664049d12c0/opentelemetry_exporter_http_transport-0.66b2.tar.gz", hash = "sha256:66d6ed810a515432c8891da9a834464332fd70badeca45bdeeae81b4280c903b", size = 11693, upload-time = "2026-10-29T17:29:39.444Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a1/b2/c622a101f31c0e6670b82f4264c4e77c161bce415bc6fc158fda0b82e218/opentelemetry_exporter_http_transport-0.66b2-py3-none-any.whl", hash = "sha256:fd5f5b490c099acda1cd7b909d5e8981436bf18cc8c6098d302d114c271720e9", size = 12154, upload-time = "2026-10-29T17:29:10.244Z" }, +] + +[package.optional-dependencies] +requests = [ + { name = "requests" }, +] + +[[package]] +name = "opentelemetry-exporter-otlp-common" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-sdk" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5a/3c/3f2cc8c42bde2620e65024d71e2eb025f7bd0821bb363b52bcc5a3260dbd/opentelemetry_exporter_otlp_common-0.66b2.tar.gz", hash = "sha256:06f5a9b88638e310efa1f1d206cdf6b75393e112aba4e174a963416192bd1028", size = 14325, upload-time = "2026-10-29T17:29:41.701Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a8/47/b3049e30b339c82e3c7ec1fc692185a5d5a3ba65a94c570bb39b2c0b8424/opentelemetry_exporter_otlp_common-0.66b2-py3-none-any.whl", hash = "sha256:ace86efb75489f925f1ef809856ae5f0c7db534e4afdc624530222228b1236a5", size = 12385, upload-time = "2026-10-29T17:29:13.667Z" }, +] + +[[package]] +name = "opentelemetry-exporter-otlp-proto-common" +version = "1.45.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-proto" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/69/58/239c98b36d9ea317098769957043c251703636a26189c884fba46c1dad84/opentelemetry_exporter_otlp_proto_common-1.45.2.tar.gz", hash = "sha256:f1f2806f3f28ce7938033823e50934fcd91595a39de38e69a28a51e19f40fc6d", size = 18873, upload-time = "2026-10-29T17:29:44.496Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e6/d6/0f30d38120a949aef70528f845bf539f80df62abb4b8e62fdf69c2b6df5a/opentelemetry_exporter_otlp_proto_common-1.45.2-py3-none-any.whl", hash = "sha256:af483b24217028892f017096731b794b196b785025d2e6808874720fd0b05a80", size = 15392, upload-time = "2026-10-29T17:29:17.913Z" }, +] + +[[package]] +name = "opentelemetry-exporter-otlp-proto-http" +version = "1.45.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "googleapis-common-protos" }, + { name = "opentelemetry-api" }, + { name = "opentelemetry-exporter-http-transport", extra = ["requests"] }, + { name = "opentelemetry-exporter-otlp-common" }, + { name = "opentelemetry-exporter-otlp-proto-common" }, + { name = "opentelemetry-proto" }, + { name = "opentelemetry-sdk" }, + { name = "requests" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/db/07/b7b01ecb69d02f540e679a9e36f7413d081f225bbbed4469d212ada10bb7/opentelemetry_exporter_otlp_proto_http-1.45.2.tar.gz", hash = "sha256:5984a3fb46bc4628e4e2b85d4a6e72637e03962aae6cf372791137768a4ad939", size = 28843, upload-time = "2026-10-29T17:29:46.15Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/65/f64d7d2450217e2989714e1dee15e19bf79a77a313387abac0cac77bc10e/opentelemetry_exporter_otlp_proto_http-1.45.2-py3-none-any.whl", hash = "sha256:6e4d025138829d0ee57946930c2ccad6491ad4d92a958e9c7eea69278fe60cfc", size = 22180, upload-time = "2026-10-29T17:29:20.154Z" }, +] + +[[package]] +name = "opentelemetry-proto" +version = "1.45.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "protobuf" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/24/9c/1aa4ce60e9bc72af20dc49c92cc0566825092d92b3d6a277439fb5fb7c01/opentelemetry_proto-1.45.2.tar.gz", hash = "sha256:bd8d23cf770605b0af9b7be2071d26a464fea289d35429abfd2a66226114ad64", size = 46486, upload-time = "2026-10-29T17:29:53.007Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/0d/a0b8f2b9efe2ec1abdf639d3696db9b1563ebeb11d91aac08ba7341e9122/opentelemetry_proto-1.45.2-py3-none-any.whl", hash = "sha256:03a7ca1b43f89fd5b965d5975902bb2515c0c86e2428b456836e9a6149c6235a", size = 72484, upload-time = "2026-10-29T17:29:31.403Z" }, +] + +[[package]] +name = "opentelemetry-sdk" +version = "1.45.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "opentelemetry-semantic-conventions" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7b/1a/74a21d4d6969fb8b432ac397e66112a8167a6deb267ea4559dbaf2fe91ef/opentelemetry_sdk-1.45.2.tar.gz", hash = "sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d", size = 221705, upload-time = "2026-10-29T17:29:54.685Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9f/a5/9a3b793ef48245f2336a16beb2324c2397dbb3f987cd68942f77cca06156/opentelemetry_sdk-1.45.2-py3-none-any.whl", hash = "sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6", size = 141756, upload-time = "2026-10-29T17:29:33.722Z" }, +] + +[[package]] +name = "opentelemetry-semantic-conventions" +version = "0.66b2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "opentelemetry-api" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/37/3f/50f95972b50e8e353f5b9342034c9cd17730f1956f009ce6a3fbbd89f9ce/opentelemetry_semantic_conventions-0.66b2.tar.gz", hash = "sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976", size = 150246, upload-time = "2026-10-29T17:29:55.682Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/67/bd/6bf33ed31521c565931c037e9e81bac47c1acb000e850c6e24220e2a0c00/opentelemetry_semantic_conventions-0.66b2-py3-none-any.whl", hash = "sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8", size = 206280, upload-time = "2026-10-29T17:29:35.062Z" }, +] + [[package]] name = "orjson" version = "3.11.2" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/df/1d/5e0ae38788bdf0721326695e65fdf41405ed535f633eb0df0f06f57552fa/orjson-3.11.2.tar.gz", hash = "sha256:91bdcf5e69a8fd8e8bdb3de32b31ff01d2bd60c1e8d5fe7d5afabdcf19920309", size = 5470739, upload-time = "2025-08-12T15:12:28.626Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/78/7d/e295df1ac9920cbb19fb4c1afa800e86f175cb657143aa422337270a4782/orjson-3.11.2-cp311-cp311-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:888b64ef7eaeeff63f773881929434a5834a6a140a63ad45183d59287f07fc6a", size = 226502, upload-time = "2025-08-12T15:10:42.284Z" }, - { url = "https://files.pythonhosted.org/packages/65/21/ffb0f10ea04caf418fb4e7ad1fda4b9ab3179df9d7a33b69420f191aadd5/orjson-3.11.2-cp311-cp311-macosx_15_0_arm64.whl", hash = "sha256:83387cc8b26c9fa0ae34d1ea8861a7ae6cff8fb3e346ab53e987d085315a728e", size = 115999, upload-time = "2025-08-12T15:10:43.738Z" }, - { url = "https://files.pythonhosted.org/packages/90/d5/8da1e252ac3353d92e6f754ee0c85027c8a2cda90b6899da2be0df3ef83d/orjson-3.11.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d7e35f003692c216d7ee901b6b916b5734d6fc4180fcaa44c52081f974c08e17", size = 111563, upload-time = "2025-08-12T15:10:45.301Z" }, - { url = "https://files.pythonhosted.org/packages/4f/81/baabc32e52c570b0e4e1044b1bd2ccbec965e0de3ba2c13082255efa2006/orjson-3.11.2-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4a0a4c29ae90b11d0c00bcc31533854d89f77bde2649ec602f512a7e16e00640", size = 116222, upload-time = "2025-08-12T15:10:46.92Z" }, - { url = "https://files.pythonhosted.org/packages/8d/b7/da2ad55ad80b49b560dce894c961477d0e76811ee6e614b301de9f2f8728/orjson-3.11.2-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:585d712b1880f68370108bc5534a257b561672d1592fae54938738fe7f6f1e33", size = 118594, upload-time = "2025-08-12T15:10:48.488Z" }, - { url = "https://files.pythonhosted.org/packages/61/be/014f7eab51449f3c894aa9bbda2707b5340c85650cb7d0db4ec9ae280501/orjson-3.11.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d08e342a7143f8a7c11f1c4033efe81acbd3c98c68ba1b26b96080396019701f", size = 120700, upload-time = "2025-08-12T15:10:49.811Z" }, - { url = "https://files.pythonhosted.org/packages/cf/ae/c217903a30c51341868e2d8c318c59a8413baa35af54d7845071c8ccd6fe/orjson-3.11.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:29c0f84fc50398773a702732c87cd622737bf11c0721e6db3041ac7802a686fb", size = 123433, upload-time = "2025-08-12T15:10:51.06Z" }, - { url = "https://files.pythonhosted.org/packages/57/c2/b3c346f78b1ff2da310dd300cb0f5d32167f872b4d3bb1ad122c889d97b0/orjson-3.11.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:140f84e3c8d4c142575898c91e3981000afebf0333df753a90b3435d349a5fe5", size = 121061, upload-time = "2025-08-12T15:10:52.381Z" }, - { url = "https://files.pythonhosted.org/packages/00/c8/c97798f6010327ffc75ad21dd6bca11ea2067d1910777e798c2849f1c68f/orjson-3.11.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:96304a2b7235e0f3f2d9363ddccdbfb027d27338722fe469fe656832a017602e", size = 119410, upload-time = "2025-08-12T15:10:53.692Z" }, - { url = "https://files.pythonhosted.org/packages/37/fd/df720f7c0e35694617b7f95598b11a2cb0374661d8389703bea17217da53/orjson-3.11.2-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:3d7612bb227d5d9582f1f50a60bd55c64618fc22c4a32825d233a4f2771a428a", size = 392294, upload-time = "2025-08-12T15:10:55.079Z" }, - { url = "https://files.pythonhosted.org/packages/ba/52/0120d18f60ab0fe47531d520372b528a45c9a25dcab500f450374421881c/orjson-3.11.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:a134587d18fe493befc2defffef2a8d27cfcada5696cb7234de54a21903ae89a", size = 134134, upload-time = "2025-08-12T15:10:56.568Z" }, - { url = "https://files.pythonhosted.org/packages/ec/10/1f967671966598366de42f07e92b0fc694ffc66eafa4b74131aeca84915f/orjson-3.11.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:0b84455e60c4bc12c1e4cbaa5cfc1acdc7775a9da9cec040e17232f4b05458bd", size = 123745, upload-time = "2025-08-12T15:10:57.907Z" }, - { url = "https://files.pythonhosted.org/packages/43/eb/76081238671461cfd0f47e0c24f408ffa66184237d56ef18c33e86abb612/orjson-3.11.2-cp311-cp311-win32.whl", hash = "sha256:f0660efeac223f0731a70884e6914a5f04d613b5ae500744c43f7bf7b78f00f9", size = 124393, upload-time = "2025-08-12T15:10:59.267Z" }, - { url = "https://files.pythonhosted.org/packages/26/76/cc598c1811ba9ba935171267b02e377fc9177489efce525d478a2999d9cc/orjson-3.11.2-cp311-cp311-win_amd64.whl", hash = "sha256:955811c8405251d9e09cbe8606ad8fdef49a451bcf5520095a5ed38c669223d8", size = 119561, upload-time = "2025-08-12T15:11:00.559Z" }, - { url = "https://files.pythonhosted.org/packages/d8/17/c48011750f0489006f7617b0a3cebc8230f36d11a34e7e9aca2085f07792/orjson-3.11.2-cp311-cp311-win_arm64.whl", hash = "sha256:2e4d423a6f838552e3a6d9ec734b729f61f88b1124fd697eab82805ea1a2a97d", size = 114186, upload-time = "2025-08-12T15:11:01.931Z" }, { url = "https://files.pythonhosted.org/packages/40/02/46054ebe7996a8adee9640dcad7d39d76c2000dc0377efa38e55dc5cbf78/orjson-3.11.2-cp312-cp312-macosx_10_15_x86_64.macosx_11_0_arm64.macosx_10_15_universal2.whl", hash = "sha256:901d80d349d8452162b3aa1afb82cec5bee79a10550660bc21311cc61a4c5486", size = 226528, upload-time = "2025-08-12T15:11:03.317Z" }, { url = "https://files.pythonhosted.org/packages/e2/c6/6b6f0b4d8aea1137436546b990f71be2cd8bd870aa2f5aa14dba0fcc95dc/orjson-3.11.2-cp312-cp312-macosx_15_0_arm64.whl", hash = "sha256:cf3bd3967a360e87ee14ed82cb258b7f18c710dacf3822fb0042a14313a673a1", size = 115931, upload-time = "2025-08-12T15:11:04.759Z" }, { url = "https://files.pythonhosted.org/packages/ae/05/4205cc97c30e82a293dd0d149b1a89b138ebe76afeca66fc129fa2aa4e6a/orjson-3.11.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:26693dde66910078229a943e80eeb99fdce6cd2c26277dc80ead9f3ab97d2131", size = 111382, upload-time = "2025-08-12T15:11:06.468Z" }, @@ -1260,14 +1230,6 @@ version = "1.10.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/92/36/44eed5ef8ce93cded76a576780bab16425ce7876f10d3e2e6265e46c21ea/ormsgpack-1.10.0.tar.gz", hash = "sha256:7f7a27efd67ef22d7182ec3b7fa7e9d147c3ad9be2a24656b23c989077e08b16", size = 58629, upload-time = "2025-05-24T19:07:53.944Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/30/27/7da748bc0d7d567950a378dee5a32477ed5d15462ab186918b5f25cac1ad/ormsgpack-1.10.0-cp311-cp311-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:4bb7df307e17b36cbf7959cd642c47a7f2046ae19408c564e437f0ec323a7775", size = 376275, upload-time = "2025-05-24T19:07:05.128Z" }, - { url = "https://files.pythonhosted.org/packages/7b/65/c082cc8c74a914dbd05af0341c761c73c3d9960b7432bbf9b8e1e20811af/ormsgpack-1.10.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8817ae439c671779e1127ee62f0ac67afdeaeeacb5f0db45703168aa74a2e4af", size = 204335, upload-time = "2025-05-24T19:07:06.423Z" }, - { url = "https://files.pythonhosted.org/packages/46/62/17ef7e5d9766c79355b9c594cc9328c204f1677bc35da0595cc4e46449f0/ormsgpack-1.10.0-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:2f345f81e852035d80232e64374d3a104139d60f8f43c6c5eade35c4bac5590e", size = 215372, upload-time = "2025-05-24T19:07:08.149Z" }, - { url = "https://files.pythonhosted.org/packages/4e/92/7c91e8115fc37e88d1a35e13200fda3054ff5d2e5adf017345e58cea4834/ormsgpack-1.10.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:21de648a1c7ef692bdd287fb08f047bd5371d7462504c0a7ae1553c39fee35e3", size = 216470, upload-time = "2025-05-24T19:07:09.903Z" }, - { url = "https://files.pythonhosted.org/packages/2c/86/ce053c52e2517b90e390792d83e926a7a523c1bce5cc63d0a7cd05ce6cf6/ormsgpack-1.10.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:3a7d844ae9cbf2112c16086dd931b2acefce14cefd163c57db161170c2bfa22b", size = 384591, upload-time = "2025-05-24T19:07:11.24Z" }, - { url = "https://files.pythonhosted.org/packages/07/e8/2ad59f2ab222c6029e500bc966bfd2fe5cb099f8ab6b7ebeb50ddb1a6fe5/ormsgpack-1.10.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:e4d80585403d86d7f800cf3d0aafac1189b403941e84e90dd5102bb2b92bf9d5", size = 478892, upload-time = "2025-05-24T19:07:13.147Z" }, - { url = "https://files.pythonhosted.org/packages/f4/73/f55e4b47b7b18fd8e7789680051bf830f1e39c03f1d9ed993cd0c3e97215/ormsgpack-1.10.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:da1de515a87e339e78a3ccf60e39f5fb740edac3e9e82d3c3d209e217a13ac08", size = 390122, upload-time = "2025-05-24T19:07:14.557Z" }, - { url = "https://files.pythonhosted.org/packages/f7/87/073251cdb93d4c6241748568b3ad1b2a76281fb2002eed16a3a4043d61cf/ormsgpack-1.10.0-cp311-cp311-win_amd64.whl", hash = "sha256:57c4601812684024132cbb32c17a7d4bb46ffc7daf2fddf5b697391c2c4f142a", size = 121197, upload-time = "2025-05-24T19:07:15.981Z" }, { url = "https://files.pythonhosted.org/packages/99/95/f3ab1a7638f6aa9362e87916bb96087fbbc5909db57e19f12ad127560e1e/ormsgpack-1.10.0-cp312-cp312-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:4e159d50cd4064d7540e2bc6a0ab66eab70b0cc40c618b485324ee17037527c0", size = 376806, upload-time = "2025-05-24T19:07:17.221Z" }, { url = "https://files.pythonhosted.org/packages/6c/2b/42f559f13c0b0f647b09d749682851d47c1a7e48308c43612ae6833499c8/ormsgpack-1.10.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:eeb47c85f3a866e29279d801115b554af0fefc409e2ed8aa90aabfa77efe5cc6", size = 204433, upload-time = "2025-05-24T19:07:18.569Z" }, { url = "https://files.pythonhosted.org/packages/45/42/1ca0cb4d8c80340a89a4af9e6d8951fb8ba0d076a899d2084eadf536f677/ormsgpack-1.10.0-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c28249574934534c9bd5dce5485c52f21bcea0ee44d13ece3def6e3d2c3798b5", size = 215547, upload-time = "2025-05-24T19:07:20.245Z" }, @@ -1300,21 +1262,13 @@ name = "pandas" version = "2.3.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", version = "1.26.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "numpy", version = "2.3.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "numpy" }, { name = "python-dateutil" }, { name = "pytz" }, { name = "tzdata" }, ] sdist = { url = "https://files.pythonhosted.org/packages/79/8e/0e90233ac205ad182bd6b422532695d2b9414944a280488105d598c70023/pandas-2.3.2.tar.gz", hash = "sha256:ab7b58f8f82706890924ccdfb5f48002b83d2b5a3845976a9fb705d36c34dcdb", size = 4488684, upload-time = "2025-08-21T10:28:29.257Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7a/59/f3e010879f118c2d400902d2d871c2226cef29b08c09fb8dc41111730400/pandas-2.3.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:1333e9c299adcbb68ee89a9bb568fc3f20f9cbb419f1dd5225071e6cddb2a743", size = 11563308, upload-time = "2025-08-21T10:26:56.656Z" }, - { url = "https://files.pythonhosted.org/packages/38/18/48f10f1cc5c397af59571d638d211f494dba481f449c19adbd282aa8f4ca/pandas-2.3.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:76972bcbd7de8e91ad5f0ca884a9f2c477a2125354af624e022c49e5bd0dfff4", size = 10820319, upload-time = "2025-08-21T10:26:59.162Z" }, - { url = "https://files.pythonhosted.org/packages/95/3b/1e9b69632898b048e223834cd9702052bcf06b15e1ae716eda3196fb972e/pandas-2.3.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b98bdd7c456a05eef7cd21fd6b29e3ca243591fe531c62be94a2cc987efb5ac2", size = 11790097, upload-time = "2025-08-21T10:27:02.204Z" }, - { url = "https://files.pythonhosted.org/packages/8b/ef/0e2ffb30b1f7fbc9a588bd01e3c14a0d96854d09a887e15e30cc19961227/pandas-2.3.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1d81573b3f7db40d020983f78721e9bfc425f411e616ef019a10ebf597aedb2e", size = 12397958, upload-time = "2025-08-21T10:27:05.409Z" }, - { url = "https://files.pythonhosted.org/packages/23/82/e6b85f0d92e9afb0e7f705a51d1399b79c7380c19687bfbf3d2837743249/pandas-2.3.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:e190b738675a73b581736cc8ec71ae113d6c3768d0bd18bffa5b9a0927b0b6ea", size = 13225600, upload-time = "2025-08-21T10:27:07.791Z" }, - { url = "https://files.pythonhosted.org/packages/e8/f1/f682015893d9ed51611948bd83683670842286a8edd4f68c2c1c3b231eef/pandas-2.3.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:c253828cb08f47488d60f43c5fc95114c771bbfff085da54bfc79cb4f9e3a372", size = 13879433, upload-time = "2025-08-21T10:27:10.347Z" }, - { url = "https://files.pythonhosted.org/packages/a7/e7/ae86261695b6c8a36d6a4c8d5f9b9ede8248510d689a2f379a18354b37d7/pandas-2.3.2-cp311-cp311-win_amd64.whl", hash = "sha256:9467697b8083f9667b212633ad6aa4ab32436dcbaf4cd57325debb0ddef2012f", size = 11336557, upload-time = "2025-08-21T10:27:12.983Z" }, { url = "https://files.pythonhosted.org/packages/ec/db/614c20fb7a85a14828edd23f1c02db58a30abf3ce76f38806155d160313c/pandas-2.3.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3fbb977f802156e7a3f829e9d1d5398f6192375a3e2d1a9ee0803e35fe70a2b9", size = 11587652, upload-time = "2025-08-21T10:27:15.888Z" }, { url = "https://files.pythonhosted.org/packages/99/b0/756e52f6582cade5e746f19bad0517ff27ba9c73404607c0306585c201b3/pandas-2.3.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1b9b52693123dd234b7c985c68b709b0b009f4521000d0525f2b95c22f15944b", size = 10717686, upload-time = "2025-08-21T10:27:18.486Z" }, { url = "https://files.pythonhosted.org/packages/37/4c/dd5ccc1e357abfeee8353123282de17997f90ff67855f86154e5a13b81e5/pandas-2.3.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0bd281310d4f412733f319a5bc552f86d62cddc5f51d2e392c8787335c994175", size = 11278722, upload-time = "2025-08-21T10:27:21.149Z" }, @@ -1343,17 +1297,6 @@ version = "11.3.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/f3/0d/d0d6dea55cd152ce3d6767bb38a8fc10e33796ba4ba210cbab9354b6d238/pillow-11.3.0.tar.gz", hash = "sha256:3828ee7586cd0b2091b6209e5ad53e20d0649bbe87164a459d0676e035e8f523", size = 47113069, upload-time = "2025-07-01T09:16:30.666Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/db/26/77f8ed17ca4ffd60e1dcd220a6ec6d71210ba398cfa33a13a1cd614c5613/pillow-11.3.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:1cd110edf822773368b396281a2293aeb91c90a2db00d78ea43e7e861631b722", size = 5316531, upload-time = "2025-07-01T09:13:59.203Z" }, - { url = "https://files.pythonhosted.org/packages/cb/39/ee475903197ce709322a17a866892efb560f57900d9af2e55f86db51b0a5/pillow-11.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9c412fddd1b77a75aa904615ebaa6001f169b26fd467b4be93aded278266b288", size = 4686560, upload-time = "2025-07-01T09:14:01.101Z" }, - { url = "https://files.pythonhosted.org/packages/d5/90/442068a160fd179938ba55ec8c97050a612426fae5ec0a764e345839f76d/pillow-11.3.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:7d1aa4de119a0ecac0a34a9c8bde33f34022e2e8f99104e47a3ca392fd60e37d", size = 5870978, upload-time = "2025-07-03T13:09:55.638Z" }, - { url = "https://files.pythonhosted.org/packages/13/92/dcdd147ab02daf405387f0218dcf792dc6dd5b14d2573d40b4caeef01059/pillow-11.3.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:91da1d88226663594e3f6b4b8c3c8d85bd504117d043740a8e0ec449087cc494", size = 7641168, upload-time = "2025-07-03T13:10:00.37Z" }, - { url = "https://files.pythonhosted.org/packages/6e/db/839d6ba7fd38b51af641aa904e2960e7a5644d60ec754c046b7d2aee00e5/pillow-11.3.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:643f189248837533073c405ec2f0bb250ba54598cf80e8c1e043381a60632f58", size = 5973053, upload-time = "2025-07-01T09:14:04.491Z" }, - { url = "https://files.pythonhosted.org/packages/f2/2f/d7675ecae6c43e9f12aa8d58b6012683b20b6edfbdac7abcb4e6af7a3784/pillow-11.3.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:106064daa23a745510dabce1d84f29137a37224831d88eb4ce94bb187b1d7e5f", size = 6640273, upload-time = "2025-07-01T09:14:06.235Z" }, - { url = "https://files.pythonhosted.org/packages/45/ad/931694675ede172e15b2ff03c8144a0ddaea1d87adb72bb07655eaffb654/pillow-11.3.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:cd8ff254faf15591e724dc7c4ddb6bf4793efcbe13802a4ae3e863cd300b493e", size = 6082043, upload-time = "2025-07-01T09:14:07.978Z" }, - { url = "https://files.pythonhosted.org/packages/3a/04/ba8f2b11fc80d2dd462d7abec16351b45ec99cbbaea4387648a44190351a/pillow-11.3.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:932c754c2d51ad2b2271fd01c3d121daaa35e27efae2a616f77bf164bc0b3e94", size = 6715516, upload-time = "2025-07-01T09:14:10.233Z" }, - { url = "https://files.pythonhosted.org/packages/48/59/8cd06d7f3944cc7d892e8533c56b0acb68399f640786313275faec1e3b6f/pillow-11.3.0-cp311-cp311-win32.whl", hash = "sha256:b4b8f3efc8d530a1544e5962bd6b403d5f7fe8b9e08227c6b255f98ad82b4ba0", size = 6274768, upload-time = "2025-07-01T09:14:11.921Z" }, - { url = "https://files.pythonhosted.org/packages/f1/cc/29c0f5d64ab8eae20f3232da8f8571660aa0ab4b8f1331da5c2f5f9a938e/pillow-11.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:1a992e86b0dd7aeb1f053cd506508c0999d710a8f07b4c791c63843fc6a807ac", size = 6986055, upload-time = "2025-07-01T09:14:13.623Z" }, - { url = "https://files.pythonhosted.org/packages/c6/df/90bd886fabd544c25addd63e5ca6932c86f2b701d5da6c7839387a076b4a/pillow-11.3.0-cp311-cp311-win_arm64.whl", hash = "sha256:30807c931ff7c095620fe04448e2c2fc673fcbb1ffe2a7da3fb39613489b1ddd", size = 2423079, upload-time = "2025-07-01T09:14:15.268Z" }, { url = "https://files.pythonhosted.org/packages/40/fe/1bc9b3ee13f68487a99ac9529968035cca2f0a51ec36892060edcc51d06a/pillow-11.3.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:fdae223722da47b024b867c1ea0be64e0df702c5e0a60e27daad39bf960dd1e4", size = 5278800, upload-time = "2025-07-01T09:14:17.648Z" }, { url = "https://files.pythonhosted.org/packages/2c/32/7e2ac19b5713657384cec55f89065fb306b06af008cfd87e572035b27119/pillow-11.3.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:921bd305b10e82b4d1f5e802b6850677f965d8394203d182f078873851dada69", size = 4686296, upload-time = "2025-07-01T09:14:19.828Z" }, { url = "https://files.pythonhosted.org/packages/8e/1e/b9e12bbe6e4c2220effebc09ea0923a07a6da1e1f1bfbc8d7d29a01ce32b/pillow-11.3.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:eb76541cba2f958032d79d143b98a3a6b3ea87f0959bbe256c0b5e416599fd5d", size = 5871726, upload-time = "2025-07-03T13:10:04.448Z" }, @@ -1412,13 +1355,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f0/77/bc6f92a3e8e6e46c0ca78abfffec0037845800ea38c73483760362804c41/pillow-11.3.0-cp314-cp314t-win32.whl", hash = "sha256:118ca10c0d60b06d006be10a501fd6bbdfef559251ed31b794668ed569c87e12", size = 6377370, upload-time = "2025-07-01T09:15:46.673Z" }, { url = "https://files.pythonhosted.org/packages/4a/82/3a721f7d69dca802befb8af08b7c79ebcab461007ce1c18bd91a5d5896f9/pillow-11.3.0-cp314-cp314t-win_amd64.whl", hash = "sha256:8924748b688aa210d79883357d102cd64690e56b923a186f35a82cbc10f997db", size = 7121500, upload-time = "2025-07-01T09:15:48.512Z" }, { url = "https://files.pythonhosted.org/packages/89/c7/5572fa4a3f45740eaab6ae86fcdf7195b55beac1371ac8c619d880cfe948/pillow-11.3.0-cp314-cp314t-win_arm64.whl", hash = "sha256:79ea0d14d3ebad43ec77ad5272e6ff9bba5b679ef73375ea760261207fa8e0aa", size = 2512835, upload-time = "2025-07-01T09:15:50.399Z" }, - { url = "https://files.pythonhosted.org/packages/9e/e3/6fa84033758276fb31da12e5fb66ad747ae83b93c67af17f8c6ff4cc8f34/pillow-11.3.0-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:7c8ec7a017ad1bd562f93dbd8505763e688d388cde6e4a010ae1486916e713e6", size = 5270566, upload-time = "2025-07-01T09:16:19.801Z" }, - { url = "https://files.pythonhosted.org/packages/5b/ee/e8d2e1ab4892970b561e1ba96cbd59c0d28cf66737fc44abb2aec3795a4e/pillow-11.3.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:9ab6ae226de48019caa8074894544af5b53a117ccb9d3b3dcb2871464c829438", size = 4654618, upload-time = "2025-07-01T09:16:21.818Z" }, - { url = "https://files.pythonhosted.org/packages/f2/6d/17f80f4e1f0761f02160fc433abd4109fa1548dcfdca46cfdadaf9efa565/pillow-11.3.0-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:fe27fb049cdcca11f11a7bfda64043c37b30e6b91f10cb5bab275806c32f6ab3", size = 4874248, upload-time = "2025-07-03T13:11:20.738Z" }, - { url = "https://files.pythonhosted.org/packages/de/5f/c22340acd61cef960130585bbe2120e2fd8434c214802f07e8c03596b17e/pillow-11.3.0-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:465b9e8844e3c3519a983d58b80be3f668e2a7a5db97f2784e7079fbc9f9822c", size = 6583963, upload-time = "2025-07-03T13:11:26.283Z" }, - { url = "https://files.pythonhosted.org/packages/31/5e/03966aedfbfcbb4d5f8aa042452d3361f325b963ebbadddac05b122e47dd/pillow-11.3.0-pp311-pypy311_pp73-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5418b53c0d59b3824d05e029669efa023bbef0f3e92e75ec8428f3799487f361", size = 4957170, upload-time = "2025-07-01T09:16:23.762Z" }, - { url = "https://files.pythonhosted.org/packages/cc/2d/e082982aacc927fc2cab48e1e731bdb1643a1406acace8bed0900a61464e/pillow-11.3.0-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:504b6f59505f08ae014f724b6207ff6222662aab5cc9542577fb084ed0676ac7", size = 5581505, upload-time = "2025-07-01T09:16:25.593Z" }, - { url = "https://files.pythonhosted.org/packages/34/e7/ae39f538fd6844e982063c3a5e4598b8ced43b9633baa3a85ef33af8c05c/pillow-11.3.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:c84d689db21a1c397d001aa08241044aa2069e7587b398c8cc63020390b1c1b8", size = 6984598, upload-time = "2025-07-01T09:16:27.732Z" }, ] [[package]] @@ -1432,16 +1368,17 @@ wheels = [ [[package]] name = "protobuf" -version = "6.32.0" +version = "6.33.6" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c0/df/fb4a8eeea482eca989b51cffd274aac2ee24e825f0bf3cbce5281fa1567b/protobuf-6.32.0.tar.gz", hash = "sha256:a81439049127067fc49ec1d36e25c6ee1d1a2b7be930675f919258d03c04e7d2", size = 440614, upload-time = "2025-08-14T21:21:25.015Z" } +sdist = { url = "https://files.pythonhosted.org/packages/66/70/e908e9c5e52ef7c3a6c7902c9dfbb34c7e29c25d2f81ade3856445fd5c94/protobuf-6.33.6.tar.gz", hash = "sha256:a6768d25248312c297558af96a9f9c929e8c4cee0659cb07e780731095f38135", size = 444531, upload-time = "2026-03-18T19:05:00.988Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/33/18/df8c87da2e47f4f1dcc5153a81cd6bca4e429803f4069a299e236e4dd510/protobuf-6.32.0-cp310-abi3-win32.whl", hash = "sha256:84f9e3c1ff6fb0308dbacb0950d8aa90694b0d0ee68e75719cb044b7078fe741", size = 424409, upload-time = "2025-08-14T21:21:12.366Z" }, - { url = "https://files.pythonhosted.org/packages/e1/59/0a820b7310f8139bd8d5a9388e6a38e1786d179d6f33998448609296c229/protobuf-6.32.0-cp310-abi3-win_amd64.whl", hash = "sha256:a8bdbb2f009cfc22a36d031f22a625a38b615b5e19e558a7b756b3279723e68e", size = 435735, upload-time = "2025-08-14T21:21:15.046Z" }, - { url = "https://files.pythonhosted.org/packages/cc/5b/0d421533c59c789e9c9894683efac582c06246bf24bb26b753b149bd88e4/protobuf-6.32.0-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:d52691e5bee6c860fff9a1c86ad26a13afbeb4b168cd4445c922b7e2cf85aaf0", size = 426449, upload-time = "2025-08-14T21:21:16.687Z" }, - { url = "https://files.pythonhosted.org/packages/ec/7b/607764ebe6c7a23dcee06e054fd1de3d5841b7648a90fd6def9a3bb58c5e/protobuf-6.32.0-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:501fe6372fd1c8ea2a30b4d9be8f87955a64d6be9c88a973996cef5ef6f0abf1", size = 322869, upload-time = "2025-08-14T21:21:18.282Z" }, - { url = "https://files.pythonhosted.org/packages/40/01/2e730bd1c25392fc32e3268e02446f0d77cb51a2c3a8486b1798e34d5805/protobuf-6.32.0-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:75a2aab2bd1aeb1f5dc7c5f33bcb11d82ea8c055c9becbb41c26a8c43fd7092c", size = 322009, upload-time = "2025-08-14T21:21:19.893Z" }, - { url = "https://files.pythonhosted.org/packages/9c/f2/80ffc4677aac1bc3519b26bc7f7f5de7fce0ee2f7e36e59e27d8beb32dd1/protobuf-6.32.0-py3-none-any.whl", hash = "sha256:ba377e5b67b908c8f3072a57b63e2c6a4cbd18aea4ed98d2584350dbf46f2783", size = 169287, upload-time = "2025-08-14T21:21:23.515Z" }, + { url = "https://files.pythonhosted.org/packages/fc/9f/2f509339e89cfa6f6a4c4ff50438db9ca488dec341f7e454adad60150b00/protobuf-6.33.6-cp310-abi3-win32.whl", hash = "sha256:7d29d9b65f8afef196f8334e80d6bc1d5d4adedb449971fefd3723824e6e77d3", size = 425739, upload-time = "2026-03-18T19:04:48.373Z" }, + { url = "https://files.pythonhosted.org/packages/76/5d/683efcd4798e0030c1bab27374fd13a89f7c2515fb1f3123efdfaa5eab57/protobuf-6.33.6-cp310-abi3-win_amd64.whl", hash = "sha256:0cd27b587afca21b7cfa59a74dcbd48a50f0a6400cfb59391340ad729d91d326", size = 437089, upload-time = "2026-03-18T19:04:50.381Z" }, + { url = "https://files.pythonhosted.org/packages/5c/01/a3c3ed5cd186f39e7880f8303cc51385a198a81469d53d0fdecf1f64d929/protobuf-6.33.6-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:9720e6961b251bde64edfdab7d500725a2af5280f3f4c87e57c0208376aa8c3a", size = 427737, upload-time = "2026-03-18T19:04:51.866Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/b3c01fdec7d2f627b3a6884243ba328c1217ed2d978def5c12dc50d328a3/protobuf-6.33.6-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:e2afbae9b8e1825e3529f88d514754e094278bb95eadc0e199751cdd9a2e82a2", size = 324610, upload-time = "2026-03-18T19:04:53.096Z" }, + { url = "https://files.pythonhosted.org/packages/9b/ca/25afc144934014700c52e05103c2421997482d561f3101ff352e1292fb81/protobuf-6.33.6-cp39-abi3-manylinux2014_s390x.whl", hash = "sha256:c96c37eec15086b79762ed265d59ab204dabc53056e3443e702d2681f4b39ce3", size = 339381, upload-time = "2026-03-18T19:04:54.616Z" }, + { url = "https://files.pythonhosted.org/packages/16/92/d1e32e3e0d894fe00b15ce28ad4944ab692713f2e7f0a99787405e43533a/protobuf-6.33.6-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:e9db7e292e0ab79dd108d7f1a94fe31601ce1ee3f7b79e0692043423020b0593", size = 323436, upload-time = "2026-03-18T19:04:55.768Z" }, + { url = "https://files.pythonhosted.org/packages/c4/72/02445137af02769918a93807b2b7890047c32bfb9f90371cbc12688819eb/protobuf-6.33.6-py3-none-any.whl", hash = "sha256:77179e006c476e69bf8e8ce866640091ec42e1beb80b213c3900006ecfba6901", size = 170656, upload-time = "2026-03-18T19:04:59.826Z" }, ] [[package]] @@ -1450,13 +1387,6 @@ version = "21.0.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/ef/c2/ea068b8f00905c06329a3dfcd40d0fcc2b7d0f2e355bdb25b65e0a0e4cd4/pyarrow-21.0.0.tar.gz", hash = "sha256:5051f2dccf0e283ff56335760cbc8622cf52264d67e359d5569541ac11b6d5bc", size = 1133487, upload-time = "2025-07-18T00:57:31.761Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/94/dc/80564a3071a57c20b7c32575e4a0120e8a330ef487c319b122942d665960/pyarrow-21.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:c077f48aab61738c237802836fc3844f85409a46015635198761b0d6a688f87b", size = 31243234, upload-time = "2025-07-18T00:55:03.812Z" }, - { url = "https://files.pythonhosted.org/packages/ea/cc/3b51cb2db26fe535d14f74cab4c79b191ed9a8cd4cbba45e2379b5ca2746/pyarrow-21.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:689f448066781856237eca8d1975b98cace19b8dd2ab6145bf49475478bcaa10", size = 32714370, upload-time = "2025-07-18T00:55:07.495Z" }, - { url = "https://files.pythonhosted.org/packages/24/11/a4431f36d5ad7d83b87146f515c063e4d07ef0b7240876ddb885e6b44f2e/pyarrow-21.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:479ee41399fcddc46159a551705b89c05f11e8b8cb8e968f7fec64f62d91985e", size = 41135424, upload-time = "2025-07-18T00:55:11.461Z" }, - { url = "https://files.pythonhosted.org/packages/74/dc/035d54638fc5d2971cbf1e987ccd45f1091c83bcf747281cf6cc25e72c88/pyarrow-21.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:40ebfcb54a4f11bcde86bc586cbd0272bac0d516cfa539c799c2453768477569", size = 42823810, upload-time = "2025-07-18T00:55:16.301Z" }, - { url = "https://files.pythonhosted.org/packages/2e/3b/89fced102448a9e3e0d4dded1f37fa3ce4700f02cdb8665457fcc8015f5b/pyarrow-21.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8d58d8497814274d3d20214fbb24abcad2f7e351474357d552a8d53bce70c70e", size = 43391538, upload-time = "2025-07-18T00:55:23.82Z" }, - { url = "https://files.pythonhosted.org/packages/fb/bb/ea7f1bd08978d39debd3b23611c293f64a642557e8141c80635d501e6d53/pyarrow-21.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:585e7224f21124dd57836b1530ac8f2df2afc43c861d7bf3d58a4870c42ae36c", size = 45120056, upload-time = "2025-07-18T00:55:28.231Z" }, - { url = "https://files.pythonhosted.org/packages/6e/0b/77ea0600009842b30ceebc3337639a7380cd946061b620ac1a2f3cb541e2/pyarrow-21.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:555ca6935b2cbca2c0e932bedd853e9bc523098c39636de9ad4693b5b1df86d6", size = 26220568, upload-time = "2025-07-18T00:55:32.122Z" }, { url = "https://files.pythonhosted.org/packages/ca/d4/d4f817b21aacc30195cf6a46ba041dd1be827efa4a623cc8bf39a1c2a0c0/pyarrow-21.0.0-cp312-cp312-macosx_12_0_arm64.whl", hash = "sha256:3a302f0e0963db37e0a24a70c56cf91a4faa0bca51c23812279ca2e23481fccd", size = 31160305, upload-time = "2025-07-18T00:55:35.373Z" }, { url = "https://files.pythonhosted.org/packages/a2/9c/dcd38ce6e4b4d9a19e1d36914cb8e2b1da4e6003dd075474c4cfcdfe0601/pyarrow-21.0.0-cp312-cp312-macosx_12_0_x86_64.whl", hash = "sha256:b6b27cf01e243871390474a211a7922bfbe3bda21e39bc9160daf0da3fe48876", size = 32684264, upload-time = "2025-07-18T00:55:39.303Z" }, { url = "https://files.pythonhosted.org/packages/4f/74/2a2d9f8d7a59b639523454bec12dba35ae3d0a07d8ab529dc0809f74b23c/pyarrow-21.0.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:e72a8ec6b868e258a2cd2672d91f2860ad532d590ce94cdf7d5e7ec674ccf03d", size = 41108099, upload-time = "2025-07-18T00:55:42.889Z" }, @@ -1504,20 +1434,6 @@ dependencies = [ ] sdist = { url = "https://files.pythonhosted.org/packages/ad/88/5f2260bdfae97aabf98f1778d43f69574390ad787afb646292a638c923d4/pydantic_core-2.33.2.tar.gz", hash = "sha256:7cb8bc3605c29176e1b105350d2e6474142d7c1bd1d9327c4a9bdb46bf827acc", size = 435195, upload-time = "2025-04-23T18:33:52.104Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/3f/8d/71db63483d518cbbf290261a1fc2839d17ff89fce7089e08cad07ccfce67/pydantic_core-2.33.2-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:4c5b0a576fb381edd6d27f0a85915c6daf2f8138dc5c267a57c08a62900758c7", size = 2028584, upload-time = "2025-04-23T18:31:03.106Z" }, - { url = "https://files.pythonhosted.org/packages/24/2f/3cfa7244ae292dd850989f328722d2aef313f74ffc471184dc509e1e4e5a/pydantic_core-2.33.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e799c050df38a639db758c617ec771fd8fb7a5f8eaaa4b27b101f266b216a246", size = 1855071, upload-time = "2025-04-23T18:31:04.621Z" }, - { url = "https://files.pythonhosted.org/packages/b3/d3/4ae42d33f5e3f50dd467761304be2fa0a9417fbf09735bc2cce003480f2a/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dc46a01bf8d62f227d5ecee74178ffc448ff4e5197c756331f71efcc66dc980f", size = 1897823, upload-time = "2025-04-23T18:31:06.377Z" }, - { url = "https://files.pythonhosted.org/packages/f4/f3/aa5976e8352b7695ff808599794b1fba2a9ae2ee954a3426855935799488/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a144d4f717285c6d9234a66778059f33a89096dfb9b39117663fd8413d582dcc", size = 1983792, upload-time = "2025-04-23T18:31:07.93Z" }, - { url = "https://files.pythonhosted.org/packages/d5/7a/cda9b5a23c552037717f2b2a5257e9b2bfe45e687386df9591eff7b46d28/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:73cf6373c21bc80b2e0dc88444f41ae60b2f070ed02095754eb5a01df12256de", size = 2136338, upload-time = "2025-04-23T18:31:09.283Z" }, - { url = "https://files.pythonhosted.org/packages/2b/9f/b8f9ec8dd1417eb9da784e91e1667d58a2a4a7b7b34cf4af765ef663a7e5/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3dc625f4aa79713512d1976fe9f0bc99f706a9dee21dfd1810b4bbbf228d0e8a", size = 2730998, upload-time = "2025-04-23T18:31:11.7Z" }, - { url = "https://files.pythonhosted.org/packages/47/bc/cd720e078576bdb8255d5032c5d63ee5c0bf4b7173dd955185a1d658c456/pydantic_core-2.33.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:881b21b5549499972441da4758d662aeea93f1923f953e9cbaff14b8b9565aef", size = 2003200, upload-time = "2025-04-23T18:31:13.536Z" }, - { url = "https://files.pythonhosted.org/packages/ca/22/3602b895ee2cd29d11a2b349372446ae9727c32e78a94b3d588a40fdf187/pydantic_core-2.33.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:bdc25f3681f7b78572699569514036afe3c243bc3059d3942624e936ec93450e", size = 2113890, upload-time = "2025-04-23T18:31:15.011Z" }, - { url = "https://files.pythonhosted.org/packages/ff/e6/e3c5908c03cf00d629eb38393a98fccc38ee0ce8ecce32f69fc7d7b558a7/pydantic_core-2.33.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:fe5b32187cbc0c862ee201ad66c30cf218e5ed468ec8dc1cf49dec66e160cc4d", size = 2073359, upload-time = "2025-04-23T18:31:16.393Z" }, - { url = "https://files.pythonhosted.org/packages/12/e7/6a36a07c59ebefc8777d1ffdaf5ae71b06b21952582e4b07eba88a421c79/pydantic_core-2.33.2-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:bc7aee6f634a6f4a95676fcb5d6559a2c2a390330098dba5e5a5f28a2e4ada30", size = 2245883, upload-time = "2025-04-23T18:31:17.892Z" }, - { url = "https://files.pythonhosted.org/packages/16/3f/59b3187aaa6cc0c1e6616e8045b284de2b6a87b027cce2ffcea073adf1d2/pydantic_core-2.33.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:235f45e5dbcccf6bd99f9f472858849f73d11120d76ea8707115415f8e5ebebf", size = 2241074, upload-time = "2025-04-23T18:31:19.205Z" }, - { url = "https://files.pythonhosted.org/packages/e0/ed/55532bb88f674d5d8f67ab121a2a13c385df382de2a1677f30ad385f7438/pydantic_core-2.33.2-cp311-cp311-win32.whl", hash = "sha256:6368900c2d3ef09b69cb0b913f9f8263b03786e5b2a387706c5afb66800efd51", size = 1910538, upload-time = "2025-04-23T18:31:20.541Z" }, - { url = "https://files.pythonhosted.org/packages/fe/1b/25b7cccd4519c0b23c2dd636ad39d381abf113085ce4f7bec2b0dc755eb1/pydantic_core-2.33.2-cp311-cp311-win_amd64.whl", hash = "sha256:1e063337ef9e9820c77acc768546325ebe04ee38b08703244c1309cccc4f1bab", size = 1952909, upload-time = "2025-04-23T18:31:22.371Z" }, - { url = "https://files.pythonhosted.org/packages/49/a9/d809358e49126438055884c4366a1f6227f0f84f635a9014e2deb9b9de54/pydantic_core-2.33.2-cp311-cp311-win_arm64.whl", hash = "sha256:6b99022f1d19bc32a4c2a0d544fc9a76e3be90f0b3f4af413f87d38749300e65", size = 1897786, upload-time = "2025-04-23T18:31:24.161Z" }, { url = "https://files.pythonhosted.org/packages/18/8a/2b41c97f554ec8c71f2a8a5f85cb56a8b0956addfe8b0efb5b3d77e8bdc3/pydantic_core-2.33.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a7ec89dc587667f22b6a0b6579c249fca9026ce7c333fc142ba42411fa243cdc", size = 2009000, upload-time = "2025-04-23T18:31:25.863Z" }, { url = "https://files.pythonhosted.org/packages/a1/02/6224312aacb3c8ecbaa959897af57181fb6cf3a3d7917fd44d0f2917e6f2/pydantic_core-2.33.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3c6db6e52c6d70aa0d00d45cdb9b40f0433b96380071ea80b09277dba021ddf7", size = 1847996, upload-time = "2025-04-23T18:31:27.341Z" }, { url = "https://files.pythonhosted.org/packages/d6/46/6dcdf084a523dbe0a0be59d054734b86a981726f221f4562aed313dbcb49/pydantic_core-2.33.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e61206137cbc65e6d5256e1166f88331d3b6238e082d9f74613b9b765fb9025", size = 1880957, upload-time = "2025-04-23T18:31:28.956Z" }, @@ -1549,15 +1465,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a4/7d/e09391c2eebeab681df2b74bfe6c43422fffede8dc74187b2b0bf6fd7571/pydantic_core-2.33.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:61c18fba8e5e9db3ab908620af374db0ac1baa69f0f32df4f61ae23f15e586ac", size = 1806162, upload-time = "2025-04-23T18:32:20.188Z" }, { url = "https://files.pythonhosted.org/packages/f1/3d/847b6b1fed9f8ed3bb95a9ad04fbd0b212e832d4f0f50ff4d9ee5a9f15cf/pydantic_core-2.33.2-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:95237e53bb015f67b63c91af7518a62a8660376a6a0db19b89acc77a4d6199f5", size = 1981560, upload-time = "2025-04-23T18:32:22.354Z" }, { url = "https://files.pythonhosted.org/packages/6f/9a/e73262f6c6656262b5fdd723ad90f518f579b7bc8622e43a942eec53c938/pydantic_core-2.33.2-cp313-cp313t-win_amd64.whl", hash = "sha256:c2fc0a768ef76c15ab9238afa6da7f69895bb5d1ee83aeea2e3509af4472d0b9", size = 1935777, upload-time = "2025-04-23T18:32:25.088Z" }, - { url = "https://files.pythonhosted.org/packages/7b/27/d4ae6487d73948d6f20dddcd94be4ea43e74349b56eba82e9bdee2d7494c/pydantic_core-2.33.2-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:dd14041875d09cc0f9308e37a6f8b65f5585cf2598a53aa0123df8b129d481f8", size = 2025200, upload-time = "2025-04-23T18:33:14.199Z" }, - { url = "https://files.pythonhosted.org/packages/f1/b8/b3cb95375f05d33801024079b9392a5ab45267a63400bf1866e7ce0f0de4/pydantic_core-2.33.2-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d87c561733f66531dced0da6e864f44ebf89a8fba55f31407b00c2f7f9449593", size = 1859123, upload-time = "2025-04-23T18:33:16.555Z" }, - { url = "https://files.pythonhosted.org/packages/05/bc/0d0b5adeda59a261cd30a1235a445bf55c7e46ae44aea28f7bd6ed46e091/pydantic_core-2.33.2-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2f82865531efd18d6e07a04a17331af02cb7a651583c418df8266f17a63c6612", size = 1892852, upload-time = "2025-04-23T18:33:18.513Z" }, - { url = "https://files.pythonhosted.org/packages/3e/11/d37bdebbda2e449cb3f519f6ce950927b56d62f0b84fd9cb9e372a26a3d5/pydantic_core-2.33.2-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2bfb5112df54209d820d7bf9317c7a6c9025ea52e49f46b6a2060104bba37de7", size = 2067484, upload-time = "2025-04-23T18:33:20.475Z" }, - { url = "https://files.pythonhosted.org/packages/8c/55/1f95f0a05ce72ecb02a8a8a1c3be0579bbc29b1d5ab68f1378b7bebc5057/pydantic_core-2.33.2-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:64632ff9d614e5eecfb495796ad51b0ed98c453e447a76bcbeeb69615079fc7e", size = 2108896, upload-time = "2025-04-23T18:33:22.501Z" }, - { url = "https://files.pythonhosted.org/packages/53/89/2b2de6c81fa131f423246a9109d7b2a375e83968ad0800d6e57d0574629b/pydantic_core-2.33.2-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:f889f7a40498cc077332c7ab6b4608d296d852182211787d4f3ee377aaae66e8", size = 2069475, upload-time = "2025-04-23T18:33:24.528Z" }, - { url = "https://files.pythonhosted.org/packages/b8/e9/1f7efbe20d0b2b10f6718944b5d8ece9152390904f29a78e68d4e7961159/pydantic_core-2.33.2-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:de4b83bb311557e439b9e186f733f6c645b9417c84e2eb8203f3f820a4b988bf", size = 2239013, upload-time = "2025-04-23T18:33:26.621Z" }, - { url = "https://files.pythonhosted.org/packages/3c/b2/5309c905a93811524a49b4e031e9851a6b00ff0fb668794472ea7746b448/pydantic_core-2.33.2-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:82f68293f055f51b51ea42fafc74b6aad03e70e191799430b90c13d643059ebb", size = 2238715, upload-time = "2025-04-23T18:33:28.656Z" }, - { url = "https://files.pythonhosted.org/packages/32/56/8a7ca5d2cd2cda1d245d34b1c9a942920a718082ae8e54e5f3e5a58b7add/pydantic_core-2.33.2-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:329467cecfb529c925cf2bbd4d60d2c509bc2fb52a20c1045bf09bb70971a9c1", size = 2066757, upload-time = "2025-04-23T18:33:30.645Z" }, ] [[package]] @@ -1580,8 +1487,7 @@ version = "0.9.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "jinja2" }, - { name = "numpy", version = "1.26.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "numpy", version = "2.3.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "numpy" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a1/ca/40e14e196864a0f61a92abb14d09b3d3da98f94ccb03b49cf51688140dab/pydeck-0.9.1.tar.gz", hash = "sha256:f74475ae637951d63f2ee58326757f8d4f9cd9f2a457cf42950715003e2cb605", size = 3832240, upload-time = "2024-05-10T15:36:21.153Z" } wheels = [ @@ -1693,9 +1599,6 @@ name = "pywin32" version = "311" source = { registry = "https://pypi.org/simple" } wheels = [ - { url = "https://files.pythonhosted.org/packages/7c/af/449a6a91e5d6db51420875c54f6aff7c97a86a3b13a0b4f1a5c13b988de3/pywin32-311-cp311-cp311-win32.whl", hash = "sha256:184eb5e436dea364dcd3d2316d577d625c0351bf237c4e9a5fabbcfa5a58b151", size = 8697031, upload-time = "2025-07-14T20:13:13.266Z" }, - { url = "https://files.pythonhosted.org/packages/51/8f/9bb81dd5bb77d22243d33c8397f09377056d5c687aa6d4042bea7fbf8364/pywin32-311-cp311-cp311-win_amd64.whl", hash = "sha256:3ce80b34b22b17ccbd937a6e78e7225d80c52f5ab9940fe0506a1a16f3dab503", size = 9508308, upload-time = "2025-07-14T20:13:15.147Z" }, - { url = "https://files.pythonhosted.org/packages/44/7b/9c2ab54f74a138c491aba1b1cd0795ba61f144c711daea84a88b63dc0f6c/pywin32-311-cp311-cp311-win_arm64.whl", hash = "sha256:a733f1388e1a842abb67ffa8e7aad0e70ac519e09b0f6a784e65a136ec7cefd2", size = 8703930, upload-time = "2025-07-14T20:13:16.945Z" }, { url = "https://files.pythonhosted.org/packages/e7/ab/01ea1943d4eba0f850c3c61e78e8dd59757ff815ff3ccd0a84de5f541f42/pywin32-311-cp312-cp312-win32.whl", hash = "sha256:750ec6e621af2b948540032557b10a2d43b0cee2ae9758c54154d711cc852d31", size = 8706543, upload-time = "2025-07-14T20:13:20.765Z" }, { url = "https://files.pythonhosted.org/packages/d1/a8/a0e8d07d4d051ec7502cd58b291ec98dcc0c3fff027caad0470b72cfcc2f/pywin32-311-cp312-cp312-win_amd64.whl", hash = "sha256:b8c095edad5c211ff31c05223658e71bf7116daa0ecf3ad85f3201ea3190d067", size = 9495040, upload-time = "2025-07-14T20:13:22.543Z" }, { url = "https://files.pythonhosted.org/packages/ba/3a/2ae996277b4b50f17d61f0603efd8253cb2d79cc7ae159468007b586396d/pywin32-311-cp312-cp312-win_arm64.whl", hash = "sha256:e286f46a9a39c4a18b319c28f59b61de793654af2f395c102b4f819e584b5852", size = 8710102, upload-time = "2025-07-14T20:13:24.682Z" }, @@ -1713,15 +1616,6 @@ version = "6.0.2" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/54/ed/79a089b6be93607fa5cdaedf301d7dfb23af5f25c398d5ead2525b063e17/pyyaml-6.0.2.tar.gz", hash = "sha256:d584d9ec91ad65861cc08d42e834324ef890a082e591037abe114850ff7bbc3e", size = 130631, upload-time = "2024-08-06T20:33:50.674Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f8/aa/7af4e81f7acba21a4c6be026da38fd2b872ca46226673c89a758ebdc4fd2/PyYAML-6.0.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cc1c1159b3d456576af7a3e4d1ba7e6924cb39de8f67111c735f6fc832082774", size = 184612, upload-time = "2024-08-06T20:32:03.408Z" }, - { url = "https://files.pythonhosted.org/packages/8b/62/b9faa998fd185f65c1371643678e4d58254add437edb764a08c5a98fb986/PyYAML-6.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1e2120ef853f59c7419231f3bf4e7021f1b936f6ebd222406c3b60212205d2ee", size = 172040, upload-time = "2024-08-06T20:32:04.926Z" }, - { url = "https://files.pythonhosted.org/packages/ad/0c/c804f5f922a9a6563bab712d8dcc70251e8af811fce4524d57c2c0fd49a4/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5d225db5a45f21e78dd9358e58a98702a0302f2659a3c6cd320564b75b86f47c", size = 736829, upload-time = "2024-08-06T20:32:06.459Z" }, - { url = "https://files.pythonhosted.org/packages/51/16/6af8d6a6b210c8e54f1406a6b9481febf9c64a3109c541567e35a49aa2e7/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5ac9328ec4831237bec75defaf839f7d4564be1e6b25ac710bd1a96321cc8317", size = 764167, upload-time = "2024-08-06T20:32:08.338Z" }, - { url = "https://files.pythonhosted.org/packages/75/e4/2c27590dfc9992f73aabbeb9241ae20220bd9452df27483b6e56d3975cc5/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ad2a3decf9aaba3d29c8f537ac4b243e36bef957511b4766cb0057d32b0be85", size = 762952, upload-time = "2024-08-06T20:32:14.124Z" }, - { url = "https://files.pythonhosted.org/packages/9b/97/ecc1abf4a823f5ac61941a9c00fe501b02ac3ab0e373c3857f7d4b83e2b6/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:ff3824dc5261f50c9b0dfb3be22b4567a6f938ccce4587b38952d85fd9e9afe4", size = 735301, upload-time = "2024-08-06T20:32:16.17Z" }, - { url = "https://files.pythonhosted.org/packages/45/73/0f49dacd6e82c9430e46f4a027baa4ca205e8b0a9dce1397f44edc23559d/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:797b4f722ffa07cc8d62053e4cff1486fa6dc094105d13fea7b1de7d8bf71c9e", size = 756638, upload-time = "2024-08-06T20:32:18.555Z" }, - { url = "https://files.pythonhosted.org/packages/22/5f/956f0f9fc65223a58fbc14459bf34b4cc48dec52e00535c79b8db361aabd/PyYAML-6.0.2-cp311-cp311-win32.whl", hash = "sha256:11d8f3dd2b9c1207dcaf2ee0bbbfd5991f571186ec9cc78427ba5bd32afae4b5", size = 143850, upload-time = "2024-08-06T20:32:19.889Z" }, - { url = "https://files.pythonhosted.org/packages/ed/23/8da0bbe2ab9dcdd11f4f4557ccaf95c10b9811b13ecced089d43ce59c3c8/PyYAML-6.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:e10ce637b18caea04431ce14fabcf5c64a1c61ec9c56b071a4b7ca131ca52d44", size = 161980, upload-time = "2024-08-06T20:32:21.273Z" }, { url = "https://files.pythonhosted.org/packages/86/0c/c581167fc46d6d6d7ddcfb8c843a4de25bdd27e4466938109ca68492292c/PyYAML-6.0.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:c70c95198c015b85feafc136515252a261a84561b7b1d51e3384e0655ddf25ab", size = 183873, upload-time = "2024-08-06T20:32:25.131Z" }, { url = "https://files.pythonhosted.org/packages/a8/0c/38374f5bb272c051e2a69281d71cba6fdb983413e6758b84482905e29a5d/PyYAML-6.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ce826d6ef20b1bc864f0a68340c8b3287705cae2f8b4b1d932177dcc76721725", size = 173302, upload-time = "2024-08-06T20:32:26.511Z" }, { url = "https://files.pythonhosted.org/packages/c3/93/9916574aa8c00aa06bbac729972eb1071d002b8e158bd0e83a3b9a20a1f7/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1f71ea527786de97d1a0cc0eacd1defc0985dcf6b3f17bb77dcfc8c34bec4dc5", size = 739154, upload-time = "2024-08-06T20:32:28.363Z" }, @@ -1747,8 +1641,7 @@ name = "rank-bm25" version = "0.2.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "numpy", version = "1.26.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "numpy", version = "2.3.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "numpy" }, ] sdist = { url = "https://files.pythonhosted.org/packages/fc/0a/f9579384aa017d8b4c15613f86954b92a95a93d641cc849182467cf0bb3b/rank_bm25-0.2.2.tar.gz", hash = "sha256:096ccef76f8188563419aaf384a02f0ea459503fdf77901378d4fd9d87e5e51d", size = 8347, upload-time = "2022-02-16T12:10:52.196Z" } wheels = [ @@ -1775,20 +1668,6 @@ version = "2025.7.34" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/0b/de/e13fa6dc61d78b30ba47481f99933a3b49a57779d625c392d8036770a60d/regex-2025.7.34.tar.gz", hash = "sha256:9ead9765217afd04a86822dfcd4ed2747dfe426e887da413b15ff0ac2457e21a", size = 400714, upload-time = "2025-07-31T00:21:16.262Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/0d/85/f497b91577169472f7c1dc262a5ecc65e39e146fc3a52c571e5daaae4b7d/regex-2025.7.34-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:da304313761b8500b8e175eb2040c4394a875837d5635f6256d6fa0377ad32c8", size = 484594, upload-time = "2025-07-31T00:19:13.927Z" }, - { url = "https://files.pythonhosted.org/packages/1c/c5/ad2a5c11ce9e6257fcbfd6cd965d07502f6054aaa19d50a3d7fd991ec5d1/regex-2025.7.34-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:35e43ebf5b18cd751ea81455b19acfdec402e82fe0dc6143edfae4c5c4b3909a", size = 289294, upload-time = "2025-07-31T00:19:15.395Z" }, - { url = "https://files.pythonhosted.org/packages/8e/01/83ffd9641fcf5e018f9b51aa922c3e538ac9439424fda3df540b643ecf4f/regex-2025.7.34-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:96bbae4c616726f4661fe7bcad5952e10d25d3c51ddc388189d8864fbc1b3c68", size = 285933, upload-time = "2025-07-31T00:19:16.704Z" }, - { url = "https://files.pythonhosted.org/packages/77/20/5edab2e5766f0259bc1da7381b07ce6eb4401b17b2254d02f492cd8a81a8/regex-2025.7.34-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9feab78a1ffa4f2b1e27b1bcdaad36f48c2fed4870264ce32f52a393db093c78", size = 792335, upload-time = "2025-07-31T00:19:18.561Z" }, - { url = "https://files.pythonhosted.org/packages/30/bd/744d3ed8777dce8487b2606b94925e207e7c5931d5870f47f5b643a4580a/regex-2025.7.34-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f14b36e6d4d07f1a5060f28ef3b3561c5d95eb0651741474ce4c0a4c56ba8719", size = 858605, upload-time = "2025-07-31T00:19:20.204Z" }, - { url = "https://files.pythonhosted.org/packages/99/3d/93754176289718d7578c31d151047e7b8acc7a8c20e7706716f23c49e45e/regex-2025.7.34-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:85c3a958ef8b3d5079c763477e1f09e89d13ad22198a37e9d7b26b4b17438b33", size = 905780, upload-time = "2025-07-31T00:19:21.876Z" }, - { url = "https://files.pythonhosted.org/packages/ee/2e/c689f274a92deffa03999a430505ff2aeace408fd681a90eafa92fdd6930/regex-2025.7.34-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:37555e4ae0b93358fa7c2d240a4291d4a4227cc7c607d8f85596cdb08ec0a083", size = 798868, upload-time = "2025-07-31T00:19:23.222Z" }, - { url = "https://files.pythonhosted.org/packages/0d/9e/39673688805d139b33b4a24851a71b9978d61915c4d72b5ffda324d0668a/regex-2025.7.34-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:ee38926f31f1aa61b0232a3a11b83461f7807661c062df9eb88769d86e6195c3", size = 781784, upload-time = "2025-07-31T00:19:24.59Z" }, - { url = "https://files.pythonhosted.org/packages/18/bd/4c1cab12cfabe14beaa076523056b8ab0c882a8feaf0a6f48b0a75dab9ed/regex-2025.7.34-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:a664291c31cae9c4a30589bd8bc2ebb56ef880c9c6264cb7643633831e606a4d", size = 852837, upload-time = "2025-07-31T00:19:25.911Z" }, - { url = "https://files.pythonhosted.org/packages/cb/21/663d983cbb3bba537fc213a579abbd0f263fb28271c514123f3c547ab917/regex-2025.7.34-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:f3e5c1e0925e77ec46ddc736b756a6da50d4df4ee3f69536ffb2373460e2dafd", size = 844240, upload-time = "2025-07-31T00:19:27.688Z" }, - { url = "https://files.pythonhosted.org/packages/8e/2d/9beeeb913bc5d32faa913cf8c47e968da936af61ec20af5d269d0f84a100/regex-2025.7.34-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d428fc7731dcbb4e2ffe43aeb8f90775ad155e7db4347a639768bc6cd2df881a", size = 787139, upload-time = "2025-07-31T00:19:29.475Z" }, - { url = "https://files.pythonhosted.org/packages/eb/f5/9b9384415fdc533551be2ba805dd8c4621873e5df69c958f403bfd3b2b6e/regex-2025.7.34-cp311-cp311-win32.whl", hash = "sha256:e154a7ee7fa18333ad90b20e16ef84daaeac61877c8ef942ec8dfa50dc38b7a1", size = 264019, upload-time = "2025-07-31T00:19:31.129Z" }, - { url = "https://files.pythonhosted.org/packages/18/9d/e069ed94debcf4cc9626d652a48040b079ce34c7e4fb174f16874958d485/regex-2025.7.34-cp311-cp311-win_amd64.whl", hash = "sha256:24257953d5c1d6d3c129ab03414c07fc1a47833c9165d49b954190b2b7f21a1a", size = 276047, upload-time = "2025-07-31T00:19:32.497Z" }, - { url = "https://files.pythonhosted.org/packages/fd/cf/3bafbe9d1fd1db77355e7fbbbf0d0cfb34501a8b8e334deca14f94c7b315/regex-2025.7.34-cp311-cp311-win_arm64.whl", hash = "sha256:3157aa512b9e606586900888cd469a444f9b898ecb7f8931996cb715f77477f0", size = 268362, upload-time = "2025-07-31T00:19:34.094Z" }, { url = "https://files.pythonhosted.org/packages/ff/f0/31d62596c75a33f979317658e8d261574785c6cd8672c06741ce2e2e2070/regex-2025.7.34-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:7f7211a746aced993bef487de69307a38c5ddd79257d7be83f7b202cb59ddb50", size = 485492, upload-time = "2025-07-31T00:19:35.57Z" }, { url = "https://files.pythonhosted.org/packages/d8/16/b818d223f1c9758c3434be89aa1a01aae798e0e0df36c1f143d1963dd1ee/regex-2025.7.34-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:fb31080f2bd0681484b275461b202b5ad182f52c9ec606052020fe13eb13a72f", size = 290000, upload-time = "2025-07-31T00:19:37.175Z" }, { url = "https://files.pythonhosted.org/packages/cd/70/69506d53397b4bd6954061bae75677ad34deb7f6ca3ba199660d6f728ff5/regex-2025.7.34-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0200a5150c4cf61e407038f4b4d5cdad13e86345dac29ff9dab3d75d905cf130", size = 286072, upload-time = "2025-07-31T00:19:38.612Z" }, @@ -1866,21 +1745,6 @@ version = "0.27.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/1e/d9/991a0dee12d9fc53ed027e26a26a64b151d77252ac477e22666b9688bc16/rpds_py-0.27.0.tar.gz", hash = "sha256:8b23cf252f180cda89220b378d917180f29d313cd6a07b2431c0d3b776aae86f", size = 27420, upload-time = "2025-08-07T08:26:39.624Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b4/c1/49d515434c1752e40f5e35b985260cf27af052593378580a2f139a5be6b8/rpds_py-0.27.0-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:dbc2ab5d10544eb485baa76c63c501303b716a5c405ff2469a1d8ceffaabf622", size = 371577, upload-time = "2025-08-07T08:23:25.379Z" }, - { url = "https://files.pythonhosted.org/packages/e1/6d/bf2715b2fee5087fa13b752b5fd573f1a93e4134c74d275f709e38e54fe7/rpds_py-0.27.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7ec85994f96a58cf7ed288caa344b7fe31fd1d503bdf13d7331ead5f70ab60d5", size = 354959, upload-time = "2025-08-07T08:23:26.767Z" }, - { url = "https://files.pythonhosted.org/packages/a3/5c/e7762808c746dd19733a81373c10da43926f6a6adcf4920a21119697a60a/rpds_py-0.27.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:190d7285cd3bb6d31d37a0534d7359c1ee191eb194c511c301f32a4afa5a1dd4", size = 381485, upload-time = "2025-08-07T08:23:27.869Z" }, - { url = "https://files.pythonhosted.org/packages/40/51/0d308eb0b558309ca0598bcba4243f52c4cd20e15fe991b5bd75824f2e61/rpds_py-0.27.0-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c10d92fb6d7fd827e44055fcd932ad93dac6a11e832d51534d77b97d1d85400f", size = 396816, upload-time = "2025-08-07T08:23:29.424Z" }, - { url = "https://files.pythonhosted.org/packages/5c/aa/2d585ec911d78f66458b2c91252134ca0c7c70f687a72c87283173dc0c96/rpds_py-0.27.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:dd2c1d27ebfe6a015cfa2005b7fe8c52d5019f7bbdd801bc6f7499aab9ae739e", size = 514950, upload-time = "2025-08-07T08:23:30.576Z" }, - { url = "https://files.pythonhosted.org/packages/0b/ef/aced551cc1148179557aed84343073adadf252c91265263ee6203458a186/rpds_py-0.27.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4790c9d5dd565ddb3e9f656092f57268951398cef52e364c405ed3112dc7c7c1", size = 402132, upload-time = "2025-08-07T08:23:32.428Z" }, - { url = "https://files.pythonhosted.org/packages/4b/ac/cf644803d8d417653fe2b3604186861d62ea6afaef1b2284045741baef17/rpds_py-0.27.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4300e15e7d03660f04be84a125d1bdd0e6b2f674bc0723bc0fd0122f1a4585dc", size = 383660, upload-time = "2025-08-07T08:23:33.829Z" }, - { url = "https://files.pythonhosted.org/packages/c9/ec/caf47c55ce02b76cbaeeb2d3b36a73da9ca2e14324e3d75cf72b59dcdac5/rpds_py-0.27.0-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:59195dc244fc183209cf8a93406889cadde47dfd2f0a6b137783aa9c56d67c85", size = 401730, upload-time = "2025-08-07T08:23:34.97Z" }, - { url = "https://files.pythonhosted.org/packages/0b/71/c1f355afdcd5b99ffc253422aa4bdcb04ccf1491dcd1bda3688a0c07fd61/rpds_py-0.27.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:fae4a01ef8c4cb2bbe92ef2063149596907dc4a881a8d26743b3f6b304713171", size = 416122, upload-time = "2025-08-07T08:23:36.062Z" }, - { url = "https://files.pythonhosted.org/packages/38/0f/f4b5b1eda724ed0e04d2b26d8911cdc131451a7ee4c4c020a1387e5c6ded/rpds_py-0.27.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:e3dc8d4ede2dbae6c0fc2b6c958bf51ce9fd7e9b40c0f5b8835c3fde44f5807d", size = 558771, upload-time = "2025-08-07T08:23:37.478Z" }, - { url = "https://files.pythonhosted.org/packages/93/c0/5f8b834db2289ab48d5cffbecbb75e35410103a77ac0b8da36bf9544ec1c/rpds_py-0.27.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:c3782fb753aa825b4ccabc04292e07897e2fd941448eabf666856c5530277626", size = 587876, upload-time = "2025-08-07T08:23:38.662Z" }, - { url = "https://files.pythonhosted.org/packages/d2/dd/1a1df02ab8eb970115cff2ae31a6f73916609b900dc86961dc382b8c2e5e/rpds_py-0.27.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:887ab1f12b0d227e9260558a4a2320024b20102207ada65c43e1ffc4546df72e", size = 554359, upload-time = "2025-08-07T08:23:39.897Z" }, - { url = "https://files.pythonhosted.org/packages/a1/e4/95a014ab0d51ab6e3bebbdb476a42d992d2bbf9c489d24cff9fda998e925/rpds_py-0.27.0-cp311-cp311-win32.whl", hash = "sha256:5d6790ff400254137b81b8053b34417e2c46921e302d655181d55ea46df58cf7", size = 218084, upload-time = "2025-08-07T08:23:41.086Z" }, - { url = "https://files.pythonhosted.org/packages/49/78/f8d5b71ec65a0376b0de31efcbb5528ce17a9b7fdd19c3763303ccfdedec/rpds_py-0.27.0-cp311-cp311-win_amd64.whl", hash = "sha256:e24d8031a2c62f34853756d9208eeafa6b940a1efcbfe36e8f57d99d52bb7261", size = 230085, upload-time = "2025-08-07T08:23:42.143Z" }, - { url = "https://files.pythonhosted.org/packages/e7/d3/84429745184091e06b4cc70f8597408e314c2d2f7f5e13249af9ffab9e3d/rpds_py-0.27.0-cp311-cp311-win_arm64.whl", hash = "sha256:08680820d23df1df0a0260f714d12966bc6c42d02e8055a91d61e03f0c47dda0", size = 222112, upload-time = "2025-08-07T08:23:43.233Z" }, { url = "https://files.pythonhosted.org/packages/cd/17/e67309ca1ac993fa1888a0d9b2f5ccc1f67196ace32e76c9f8e1dbbbd50c/rpds_py-0.27.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:19c990fdf5acecbf0623e906ae2e09ce1c58947197f9bced6bbd7482662231c4", size = 362611, upload-time = "2025-08-07T08:23:44.773Z" }, { url = "https://files.pythonhosted.org/packages/93/2e/28c2fb84aa7aa5d75933d1862d0f7de6198ea22dfd9a0cca06e8a4e7509e/rpds_py-0.27.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6c27a7054b5224710fcfb1a626ec3ff4f28bcb89b899148c72873b18210e446b", size = 347680, upload-time = "2025-08-07T08:23:46.014Z" }, { url = "https://files.pythonhosted.org/packages/44/3e/9834b4c8f4f5fe936b479e623832468aa4bd6beb8d014fecaee9eac6cdb1/rpds_py-0.27.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:09965b314091829b378b60607022048953e25f0b396c2b70e7c4c81bcecf932e", size = 384600, upload-time = "2025-08-07T08:23:48Z" }, @@ -1954,18 +1818,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/63/09/ee1bb5536f99f42c839b177d552f6114aa3142d82f49cef49261ed28dbe0/rpds_py-0.27.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:3001013dae10f806380ba739d40dee11db1ecb91684febb8406a87c2ded23dae", size = 555090, upload-time = "2025-08-07T08:25:20.461Z" }, { url = "https://files.pythonhosted.org/packages/7d/2c/363eada9e89f7059199d3724135a86c47082cbf72790d6ba2f336d146ddb/rpds_py-0.27.0-cp314-cp314t-win32.whl", hash = "sha256:0f401c369186a5743694dd9fc08cba66cf70908757552e1f714bfc5219c655b5", size = 218001, upload-time = "2025-08-07T08:25:21.761Z" }, { url = "https://files.pythonhosted.org/packages/e2/3f/d6c216ed5199c9ef79e2a33955601f454ed1e7420a93b89670133bca5ace/rpds_py-0.27.0-cp314-cp314t-win_amd64.whl", hash = "sha256:8a1dca5507fa1337f75dcd5070218b20bc68cf8844271c923c1b79dfcbc20391", size = 230993, upload-time = "2025-08-07T08:25:23.34Z" }, - { url = "https://files.pythonhosted.org/packages/59/64/72ab5b911fdcc48058359b0e786e5363e3fde885156116026f1a2ba9a5b5/rpds_py-0.27.0-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:e6491658dd2569f05860bad645569145c8626ac231877b0fb2d5f9bcb7054089", size = 371658, upload-time = "2025-08-07T08:26:02.369Z" }, - { url = "https://files.pythonhosted.org/packages/6c/4b/90ff04b4da055db53d8fea57640d8d5d55456343a1ec9a866c0ecfe10fd1/rpds_py-0.27.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:bec77545d188f8bdd29d42bccb9191682a46fb2e655e3d1fb446d47c55ac3b8d", size = 355529, upload-time = "2025-08-07T08:26:03.83Z" }, - { url = "https://files.pythonhosted.org/packages/a4/be/527491fb1afcd86fc5ce5812eb37bc70428ee017d77fee20de18155c3937/rpds_py-0.27.0-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:25a4aebf8ca02bbb90a9b3e7a463bbf3bee02ab1c446840ca07b1695a68ce424", size = 382822, upload-time = "2025-08-07T08:26:05.52Z" }, - { url = "https://files.pythonhosted.org/packages/e0/a5/dcdb8725ce11e6d0913e6fcf782a13f4b8a517e8acc70946031830b98441/rpds_py-0.27.0-pp311-pypy311_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:44524b96481a4c9b8e6c46d6afe43fa1fb485c261e359fbe32b63ff60e3884d8", size = 397233, upload-time = "2025-08-07T08:26:07.179Z" }, - { url = "https://files.pythonhosted.org/packages/33/f9/0947920d1927e9f144660590cc38cadb0795d78fe0d9aae0ef71c1513b7c/rpds_py-0.27.0-pp311-pypy311_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:45d04a73c54b6a5fd2bab91a4b5bc8b426949586e61340e212a8484919183859", size = 514892, upload-time = "2025-08-07T08:26:08.622Z" }, - { url = "https://files.pythonhosted.org/packages/1d/ed/d1343398c1417c68f8daa1afce56ef6ce5cc587daaf98e29347b00a80ff2/rpds_py-0.27.0-pp311-pypy311_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:343cf24de9ed6c728abefc5d5c851d5de06497caa7ac37e5e65dd572921ed1b5", size = 402733, upload-time = "2025-08-07T08:26:10.433Z" }, - { url = "https://files.pythonhosted.org/packages/1d/0b/646f55442cd14014fb64d143428f25667a100f82092c90087b9ea7101c74/rpds_py-0.27.0-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7aed8118ae20515974650d08eb724150dc2e20c2814bcc307089569995e88a14", size = 384447, upload-time = "2025-08-07T08:26:11.847Z" }, - { url = "https://files.pythonhosted.org/packages/4b/15/0596ef7529828e33a6c81ecf5013d1dd33a511a3e0be0561f83079cda227/rpds_py-0.27.0-pp311-pypy311_pp73-manylinux_2_31_riscv64.whl", hash = "sha256:af9d4fd79ee1cc8e7caf693ee02737daabfc0fcf2773ca0a4735b356c8ad6f7c", size = 402502, upload-time = "2025-08-07T08:26:13.537Z" }, - { url = "https://files.pythonhosted.org/packages/c3/8d/986af3c42f8454a6cafff8729d99fb178ae9b08a9816325ac7a8fa57c0c0/rpds_py-0.27.0-pp311-pypy311_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f0396e894bd1e66c74ecbc08b4f6a03dc331140942c4b1d345dd131b68574a60", size = 416651, upload-time = "2025-08-07T08:26:14.923Z" }, - { url = "https://files.pythonhosted.org/packages/e9/9a/b4ec3629b7b447e896eec574469159b5b60b7781d3711c914748bf32de05/rpds_py-0.27.0-pp311-pypy311_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:59714ab0a5af25d723d8e9816638faf7f4254234decb7d212715c1aa71eee7be", size = 559460, upload-time = "2025-08-07T08:26:16.295Z" }, - { url = "https://files.pythonhosted.org/packages/61/63/d1e127b40c3e4733b3a6f26ae7a063cdf2bc1caa5272c89075425c7d397a/rpds_py-0.27.0-pp311-pypy311_pp73-musllinux_1_2_i686.whl", hash = "sha256:88051c3b7d5325409f433c5a40328fcb0685fc04e5db49ff936e910901d10114", size = 588072, upload-time = "2025-08-07T08:26:17.776Z" }, - { url = "https://files.pythonhosted.org/packages/04/7e/8ffc71a8f6833d9c9fb999f5b0ee736b8b159fd66968e05c7afc2dbcd57e/rpds_py-0.27.0-pp311-pypy311_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:181bc29e59e5e5e6e9d63b143ff4d5191224d355e246b5a48c88ce6b35c4e466", size = 555083, upload-time = "2025-08-07T08:26:19.301Z" }, ] [[package]] @@ -2006,20 +1858,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/48/f0/ae7ca09223a81a1d890b2557186ea015f6e0502e9b8cb8e1813f1d8cfa4e/s3transfer-0.14.0-py3-none-any.whl", hash = "sha256:ea3b790c7077558ed1f02a3072fb3cb992bbbd253392f4b6e9e8976941c7d456", size = 85712, upload-time = "2025-09-09T19:23:30.041Z" }, ] -[[package]] -name = "semanticscholar" -version = "0.10.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "httpx" }, - { name = "nest-asyncio" }, - { name = "tenacity" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/69/90/3034058446c39b7069baaa2476c3d7649af3729d99137e85f57ae95de460/semanticscholar-0.10.0.tar.gz", hash = "sha256:82f907265aebcb1d9432b1cdd880d706230444515a4b94017358b938d007dbec", size = 24318, upload-time = "2025-02-17T02:38:25.25Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/21/3e/f59d7b485230763f278ece2abece586cd0725512786a4db04b05729d566a/semanticscholar-0.10.0-py3-none-any.whl", hash = "sha256:28a572eb8504d493ab5671bc3ce76f84ae70534a5828ec0cd38a26f27e66bd02", size = 22416, upload-time = "2025-02-17T02:38:24.149Z" }, -] - [[package]] name = "semver" version = "3.0.4" @@ -2075,14 +1913,6 @@ dependencies = [ ] sdist = { url = "https://files.pythonhosted.org/packages/d7/bc/d59b5d97d27229b0e009bd9098cd81af71c2fa5549c580a0a67b9bed0496/sqlalchemy-2.0.43.tar.gz", hash = "sha256:788bfcef6787a7764169cfe9859fe425bf44559619e1d9f56f5bddf2ebf6f417", size = 9762949, upload-time = "2025-08-11T14:24:58.438Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9d/77/fa7189fe44114658002566c6fe443d3ed0ec1fa782feb72af6ef7fbe98e7/sqlalchemy-2.0.43-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:52d9b73b8fb3e9da34c2b31e6d99d60f5f99fd8c1225c9dad24aeb74a91e1d29", size = 2136472, upload-time = "2025-08-11T15:52:21.789Z" }, - { url = "https://files.pythonhosted.org/packages/99/ea/92ac27f2fbc2e6c1766bb807084ca455265707e041ba027c09c17d697867/sqlalchemy-2.0.43-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f42f23e152e4545157fa367b2435a1ace7571cab016ca26038867eb7df2c3631", size = 2126535, upload-time = "2025-08-11T15:52:23.109Z" }, - { url = "https://files.pythonhosted.org/packages/94/12/536ede80163e295dc57fff69724caf68f91bb40578b6ac6583a293534849/sqlalchemy-2.0.43-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4fb1a8c5438e0c5ea51afe9c6564f951525795cf432bed0c028c1cb081276685", size = 3297521, upload-time = "2025-08-11T15:50:33.536Z" }, - { url = "https://files.pythonhosted.org/packages/03/b5/cacf432e6f1fc9d156eca0560ac61d4355d2181e751ba8c0cd9cb232c8c1/sqlalchemy-2.0.43-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:db691fa174e8f7036afefe3061bc40ac2b770718be2862bfb03aabae09051aca", size = 3297343, upload-time = "2025-08-11T15:57:51.186Z" }, - { url = "https://files.pythonhosted.org/packages/ca/ba/d4c9b526f18457667de4c024ffbc3a0920c34237b9e9dd298e44c7c00ee5/sqlalchemy-2.0.43-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:fe2b3b4927d0bc03d02ad883f402d5de201dbc8894ac87d2e981e7d87430e60d", size = 3232113, upload-time = "2025-08-11T15:50:34.949Z" }, - { url = "https://files.pythonhosted.org/packages/aa/79/c0121b12b1b114e2c8a10ea297a8a6d5367bc59081b2be896815154b1163/sqlalchemy-2.0.43-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4d3d9b904ad4a6b175a2de0738248822f5ac410f52c2fd389ada0b5262d6a1e3", size = 3258240, upload-time = "2025-08-11T15:57:52.983Z" }, - { url = "https://files.pythonhosted.org/packages/79/99/a2f9be96fb382f3ba027ad42f00dbe30fdb6ba28cda5f11412eee346bec5/sqlalchemy-2.0.43-cp311-cp311-win32.whl", hash = "sha256:5cda6b51faff2639296e276591808c1726c4a77929cfaa0f514f30a5f6156921", size = 2101248, upload-time = "2025-08-11T15:55:01.855Z" }, - { url = "https://files.pythonhosted.org/packages/ee/13/744a32ebe3b4a7a9c7ea4e57babae7aa22070d47acf330d8e5a1359607f1/sqlalchemy-2.0.43-cp311-cp311-win_amd64.whl", hash = "sha256:c5d1730b25d9a07727d20ad74bc1039bbbb0a6ca24e6769861c1aa5bf2c4c4a8", size = 2126109, upload-time = "2025-08-11T15:55:04.092Z" }, { url = "https://files.pythonhosted.org/packages/61/db/20c78f1081446095450bdc6ee6cc10045fce67a8e003a5876b6eaafc5cc4/sqlalchemy-2.0.43-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:20d81fc2736509d7a2bd33292e489b056cbae543661bb7de7ce9f1c0cd6e7f24", size = 2134891, upload-time = "2025-08-11T15:51:13.019Z" }, { url = "https://files.pythonhosted.org/packages/45/0a/3d89034ae62b200b4396f0f95319f7d86e9945ee64d2343dcad857150fa2/sqlalchemy-2.0.43-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:25b9fc27650ff5a2c9d490c13c14906b918b0de1f8fcbb4c992712d8caf40e83", size = 2123061, upload-time = "2025-08-11T15:51:14.319Z" }, { url = "https://files.pythonhosted.org/packages/cb/10/2711f7ff1805919221ad5bee205971254845c069ee2e7036847103ca1e4c/sqlalchemy-2.0.43-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6772e3ca8a43a65a37c88e2f3e2adfd511b0b1da37ef11ed78dea16aeae85bd9", size = 3320384, upload-time = "2025-08-11T15:52:35.088Z" }, @@ -2137,8 +1967,7 @@ dependencies = [ { name = "cachetools" }, { name = "click" }, { name = "gitpython" }, - { name = "numpy", version = "1.26.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "numpy", version = "2.3.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "numpy" }, { name = "packaging" }, { name = "pandas" }, { name = "pillow" }, @@ -2176,12 +2005,6 @@ dependencies = [ ] sdist = { url = "https://files.pythonhosted.org/packages/a7/86/ad0155a37c4f310935d5ac0b1ccf9bdb635dcb906e0a9a26b616dd55825a/tiktoken-0.11.0.tar.gz", hash = "sha256:3c518641aee1c52247c2b97e74d8d07d780092af79d5911a6ab5e79359d9b06a", size = 37648, upload-time = "2025-08-08T23:58:08.495Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/8a/91/912b459799a025d2842566fe1e902f7f50d54a1ce8a0f236ab36b5bd5846/tiktoken-0.11.0-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:4ae374c46afadad0f501046db3da1b36cd4dfbfa52af23c998773682446097cf", size = 1059743, upload-time = "2025-08-08T23:57:37.516Z" }, - { url = "https://files.pythonhosted.org/packages/8c/e9/6faa6870489ce64f5f75dcf91512bf35af5864583aee8fcb0dcb593121f5/tiktoken-0.11.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:25a512ff25dc6c85b58f5dd4f3d8c674dc05f96b02d66cdacf628d26a4e4866b", size = 999334, upload-time = "2025-08-08T23:57:38.595Z" }, - { url = "https://files.pythonhosted.org/packages/a1/3e/a05d1547cf7db9dc75d1461cfa7b556a3b48e0516ec29dfc81d984a145f6/tiktoken-0.11.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2130127471e293d385179c1f3f9cd445070c0772be73cdafb7cec9a3684c0458", size = 1129402, upload-time = "2025-08-08T23:57:39.627Z" }, - { url = "https://files.pythonhosted.org/packages/34/9a/db7a86b829e05a01fd4daa492086f708e0a8b53952e1dbc9d380d2b03677/tiktoken-0.11.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:21e43022bf2c33f733ea9b54f6a3f6b4354b909f5a73388fb1b9347ca54a069c", size = 1184046, upload-time = "2025-08-08T23:57:40.689Z" }, - { url = "https://files.pythonhosted.org/packages/9d/bb/52edc8e078cf062ed749248f1454e9e5cfd09979baadb830b3940e522015/tiktoken-0.11.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:adb4e308eb64380dc70fa30493e21c93475eaa11669dea313b6bbf8210bfd013", size = 1244691, upload-time = "2025-08-08T23:57:42.251Z" }, - { url = "https://files.pythonhosted.org/packages/60/d9/884b6cd7ae2570ecdcaffa02b528522b18fef1cbbfdbcaa73799807d0d3b/tiktoken-0.11.0-cp311-cp311-win_amd64.whl", hash = "sha256:ece6b76bfeeb61a125c44bbefdfccc279b5288e6007fbedc0d32bfec602df2f2", size = 884392, upload-time = "2025-08-08T23:57:43.628Z" }, { url = "https://files.pythonhosted.org/packages/e7/9e/eceddeffc169fc75fe0fd4f38471309f11cb1906f9b8aa39be4f5817df65/tiktoken-0.11.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:fd9e6b23e860973cf9526544e220b223c60badf5b62e80a33509d6d40e6c8f5d", size = 1055199, upload-time = "2025-08-08T23:57:45.076Z" }, { url = "https://files.pythonhosted.org/packages/4f/cf/5f02bfefffdc6b54e5094d2897bc80efd43050e5b09b576fd85936ee54bf/tiktoken-0.11.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:6a76d53cee2da71ee2731c9caa747398762bda19d7f92665e882fef229cb0b5b", size = 996655, upload-time = "2025-08-08T23:57:46.304Z" }, { url = "https://files.pythonhosted.org/packages/65/8e/c769b45ef379bc360c9978c4f6914c79fd432400a6733a8afc7ed7b0726a/tiktoken-0.11.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6ef72aab3ea240646e642413cb363b73869fed4e604dcfd69eec63dc54d603e8", size = 1128867, upload-time = "2025-08-08T23:57:47.438Z" }, @@ -2330,12 +2153,6 @@ version = "0.21.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/af/c0/854216d09d33c543f12a44b393c402e89a920b1a0a7dc634c42de91b9cf6/uvloop-0.21.0.tar.gz", hash = "sha256:3bf12b0fda68447806a7ad847bfa591613177275d35b6724b1ee573faa3704e3", size = 2492741, upload-time = "2024-10-14T23:38:35.489Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/57/a7/4cf0334105c1160dd6819f3297f8700fda7fc30ab4f61fbf3e725acbc7cc/uvloop-0.21.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:c0f3fa6200b3108919f8bdabb9a7f87f20e7097ea3c543754cabc7d717d95cf8", size = 1447410, upload-time = "2024-10-14T23:37:33.612Z" }, - { url = "https://files.pythonhosted.org/packages/8c/7c/1517b0bbc2dbe784b563d6ab54f2ef88c890fdad77232c98ed490aa07132/uvloop-0.21.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:0878c2640cf341b269b7e128b1a5fed890adc4455513ca710d77d5e93aa6d6a0", size = 805476, upload-time = "2024-10-14T23:37:36.11Z" }, - { url = "https://files.pythonhosted.org/packages/ee/ea/0bfae1aceb82a503f358d8d2fa126ca9dbdb2ba9c7866974faec1cb5875c/uvloop-0.21.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b9fb766bb57b7388745d8bcc53a359b116b8a04c83a2288069809d2b3466c37e", size = 3960855, upload-time = "2024-10-14T23:37:37.683Z" }, - { url = "https://files.pythonhosted.org/packages/8a/ca/0864176a649838b838f36d44bf31c451597ab363b60dc9e09c9630619d41/uvloop-0.21.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8a375441696e2eda1c43c44ccb66e04d61ceeffcd76e4929e527b7fa401b90fb", size = 3973185, upload-time = "2024-10-14T23:37:40.226Z" }, - { url = "https://files.pythonhosted.org/packages/30/bf/08ad29979a936d63787ba47a540de2132169f140d54aa25bc8c3df3e67f4/uvloop-0.21.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:baa0e6291d91649c6ba4ed4b2f982f9fa165b5bbd50a9e203c416a2797bab3c6", size = 3820256, upload-time = "2024-10-14T23:37:42.839Z" }, - { url = "https://files.pythonhosted.org/packages/da/e2/5cf6ef37e3daf2f06e651aae5ea108ad30df3cb269102678b61ebf1fdf42/uvloop-0.21.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4509360fcc4c3bd2c70d87573ad472de40c13387f5fda8cb58350a1d7475e58d", size = 3937323, upload-time = "2024-10-14T23:37:45.337Z" }, { url = "https://files.pythonhosted.org/packages/8c/4c/03f93178830dc7ce8b4cdee1d36770d2f5ebb6f3d37d354e061eefc73545/uvloop-0.21.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:359ec2c888397b9e592a889c4d72ba3d6befba8b2bb01743f72fffbde663b59c", size = 1471284, upload-time = "2024-10-14T23:37:47.833Z" }, { url = "https://files.pythonhosted.org/packages/43/3e/92c03f4d05e50f09251bd8b2b2b584a2a7f8fe600008bcc4523337abe676/uvloop-0.21.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:f7089d2dc73179ce5ac255bdf37c236a9f914b264825fdaacaded6990a7fb4c2", size = 821349, upload-time = "2024-10-14T23:37:50.149Z" }, { url = "https://files.pythonhosted.org/packages/a6/ef/a02ec5da49909dbbfb1fd205a9a1ac4e88ea92dcae885e7c961847cd51e2/uvloop-0.21.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:baa4dcdbd9ae0a372f2167a207cd98c9f9a1ea1188a8a526431eef2f8116cc8d", size = 4580089, upload-time = "2024-10-14T23:37:51.703Z" }, @@ -2377,19 +2194,6 @@ dependencies = [ ] sdist = { url = "https://files.pythonhosted.org/packages/2a/9a/d451fcc97d029f5812e898fd30a53fd8c15c7bbd058fd75cfc6beb9bd761/watchfiles-1.1.0.tar.gz", hash = "sha256:693ed7ec72cbfcee399e92c895362b6e66d63dac6b91e2c11ae03d10d503e575", size = 94406, upload-time = "2025-06-15T19:06:59.42Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/8b/78/7401154b78ab484ccaaeef970dc2af0cb88b5ba8a1b415383da444cdd8d3/watchfiles-1.1.0-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:c9649dfc57cc1f9835551deb17689e8d44666315f2e82d337b9f07bd76ae3aa2", size = 405751, upload-time = "2025-06-15T19:05:07.679Z" }, - { url = "https://files.pythonhosted.org/packages/76/63/e6c3dbc1f78d001589b75e56a288c47723de28c580ad715eb116639152b5/watchfiles-1.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:406520216186b99374cdb58bc48e34bb74535adec160c8459894884c983a149c", size = 397313, upload-time = "2025-06-15T19:05:08.764Z" }, - { url = "https://files.pythonhosted.org/packages/6c/a2/8afa359ff52e99af1632f90cbf359da46184207e893a5f179301b0c8d6df/watchfiles-1.1.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cb45350fd1dc75cd68d3d72c47f5b513cb0578da716df5fba02fff31c69d5f2d", size = 450792, upload-time = "2025-06-15T19:05:09.869Z" }, - { url = "https://files.pythonhosted.org/packages/1d/bf/7446b401667f5c64972a57a0233be1104157fc3abf72c4ef2666c1bd09b2/watchfiles-1.1.0-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:11ee4444250fcbeb47459a877e5e80ed994ce8e8d20283857fc128be1715dac7", size = 458196, upload-time = "2025-06-15T19:05:11.91Z" }, - { url = "https://files.pythonhosted.org/packages/58/2f/501ddbdfa3fa874ea5597c77eeea3d413579c29af26c1091b08d0c792280/watchfiles-1.1.0-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bda8136e6a80bdea23e5e74e09df0362744d24ffb8cd59c4a95a6ce3d142f79c", size = 484788, upload-time = "2025-06-15T19:05:13.373Z" }, - { url = "https://files.pythonhosted.org/packages/61/1e/9c18eb2eb5c953c96bc0e5f626f0e53cfef4bd19bd50d71d1a049c63a575/watchfiles-1.1.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b915daeb2d8c1f5cee4b970f2e2c988ce6514aace3c9296e58dd64dc9aa5d575", size = 597879, upload-time = "2025-06-15T19:05:14.725Z" }, - { url = "https://files.pythonhosted.org/packages/8b/6c/1467402e5185d89388b4486745af1e0325007af0017c3384cc786fff0542/watchfiles-1.1.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ed8fc66786de8d0376f9f913c09e963c66e90ced9aa11997f93bdb30f7c872a8", size = 477447, upload-time = "2025-06-15T19:05:15.775Z" }, - { url = "https://files.pythonhosted.org/packages/2b/a1/ec0a606bde4853d6c4a578f9391eeb3684a9aea736a8eb217e3e00aa89a1/watchfiles-1.1.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fe4371595edf78c41ef8ac8df20df3943e13defd0efcb732b2e393b5a8a7a71f", size = 453145, upload-time = "2025-06-15T19:05:17.17Z" }, - { url = "https://files.pythonhosted.org/packages/90/b9/ef6f0c247a6a35d689fc970dc7f6734f9257451aefb30def5d100d6246a5/watchfiles-1.1.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:b7c5f6fe273291f4d414d55b2c80d33c457b8a42677ad14b4b47ff025d0893e4", size = 626539, upload-time = "2025-06-15T19:05:18.557Z" }, - { url = "https://files.pythonhosted.org/packages/34/44/6ffda5537085106ff5aaa762b0d130ac6c75a08015dd1621376f708c94de/watchfiles-1.1.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:7738027989881e70e3723c75921f1efa45225084228788fc59ea8c6d732eb30d", size = 624472, upload-time = "2025-06-15T19:05:19.588Z" }, - { url = "https://files.pythonhosted.org/packages/c3/e3/71170985c48028fa3f0a50946916a14055e741db11c2e7bc2f3b61f4d0e3/watchfiles-1.1.0-cp311-cp311-win32.whl", hash = "sha256:622d6b2c06be19f6e89b1d951485a232e3b59618def88dbeda575ed8f0d8dbf2", size = 279348, upload-time = "2025-06-15T19:05:20.856Z" }, - { url = "https://files.pythonhosted.org/packages/89/1b/3e39c68b68a7a171070f81fc2561d23ce8d6859659406842a0e4bebf3bba/watchfiles-1.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:48aa25e5992b61debc908a61ab4d3f216b64f44fdaa71eb082d8b2de846b7d12", size = 292607, upload-time = "2025-06-15T19:05:21.937Z" }, - { url = "https://files.pythonhosted.org/packages/61/9f/2973b7539f2bdb6ea86d2c87f70f615a71a1fc2dba2911795cea25968aea/watchfiles-1.1.0-cp311-cp311-win_arm64.whl", hash = "sha256:00645eb79a3faa70d9cb15c8d4187bb72970b2470e938670240c7998dad9f13a", size = 285056, upload-time = "2025-06-15T19:05:23.12Z" }, { url = "https://files.pythonhosted.org/packages/f6/b8/858957045a38a4079203a33aaa7d23ea9269ca7761c8a074af3524fbb240/watchfiles-1.1.0-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:9dc001c3e10de4725c749d4c2f2bdc6ae24de5a88a339c4bce32300a31ede179", size = 402339, upload-time = "2025-06-15T19:05:24.516Z" }, { url = "https://files.pythonhosted.org/packages/80/28/98b222cca751ba68e88521fabd79a4fab64005fc5976ea49b53fa205d1fa/watchfiles-1.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:d9ba68ec283153dead62cbe81872d28e053745f12335d037de9cbd14bd1877f5", size = 394409, upload-time = "2025-06-15T19:05:25.469Z" }, { url = "https://files.pythonhosted.org/packages/86/50/dee79968566c03190677c26f7f47960aff738d32087087bdf63a5473e7df/watchfiles-1.1.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:130fc497b8ee68dce163e4254d9b0356411d1490e868bd8790028bc46c5cc297", size = 450939, upload-time = "2025-06-15T19:05:26.494Z" }, @@ -2446,10 +2250,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/69/c4/088825b75489cb5b6a761a4542645718893d395d8c530b38734f19da44d2/watchfiles-1.1.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d05686b5487cfa2e2c28ff1aa370ea3e6c5accfe6435944ddea1e10d93872147", size = 452240, upload-time = "2025-06-15T19:06:26.552Z" }, { url = "https://files.pythonhosted.org/packages/10/8c/22b074814970eeef43b7c44df98c3e9667c1f7bf5b83e0ff0201b0bd43f9/watchfiles-1.1.0-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:d0e10e6f8f6dc5762adee7dece33b722282e1f59aa6a55da5d493a97282fedd8", size = 625607, upload-time = "2025-06-15T19:06:27.606Z" }, { url = "https://files.pythonhosted.org/packages/32/fa/a4f5c2046385492b2273213ef815bf71a0d4c1943b784fb904e184e30201/watchfiles-1.1.0-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:af06c863f152005c7592df1d6a7009c836a247c9d8adb78fef8575a5a98699db", size = 623315, upload-time = "2025-06-15T19:06:29.076Z" }, - { url = "https://files.pythonhosted.org/packages/8c/6b/686dcf5d3525ad17b384fd94708e95193529b460a1b7bf40851f1328ec6e/watchfiles-1.1.0-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:0ece16b563b17ab26eaa2d52230c9a7ae46cf01759621f4fbbca280e438267b3", size = 406910, upload-time = "2025-06-15T19:06:49.335Z" }, - { url = "https://files.pythonhosted.org/packages/f3/d3/71c2dcf81dc1edcf8af9f4d8d63b1316fb0a2dd90cbfd427e8d9dd584a90/watchfiles-1.1.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:51b81e55d40c4b4aa8658427a3ee7ea847c591ae9e8b81ef94a90b668999353c", size = 398816, upload-time = "2025-06-15T19:06:50.433Z" }, - { url = "https://files.pythonhosted.org/packages/b8/fa/12269467b2fc006f8fce4cd6c3acfa77491dd0777d2a747415f28ccc8c60/watchfiles-1.1.0-pp311-pypy311_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f2bcdc54ea267fe72bfc7d83c041e4eb58d7d8dc6f578dfddb52f037ce62f432", size = 451584, upload-time = "2025-06-15T19:06:51.834Z" }, - { url = "https://files.pythonhosted.org/packages/bd/d3/254cea30f918f489db09d6a8435a7de7047f8cb68584477a515f160541d6/watchfiles-1.1.0-pp311-pypy311_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:923fec6e5461c42bd7e3fd5ec37492c6f3468be0499bc0707b4bbbc16ac21792", size = 454009, upload-time = "2025-06-15T19:06:52.896Z" }, ] [[package]] @@ -2458,17 +2258,6 @@ version = "15.0.1" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/21/e6/26d09fab466b7ca9c7737474c52be4f76a40301b08362eb2dbc19dcc16c1/websockets-15.0.1.tar.gz", hash = "sha256:82544de02076bafba038ce055ee6412d68da13ab47f0c60cab827346de828dee", size = 177016, upload-time = "2025-03-05T20:03:41.606Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/9f/32/18fcd5919c293a398db67443acd33fde142f283853076049824fc58e6f75/websockets-15.0.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:823c248b690b2fd9303ba00c4f66cd5e2d8c3ba4aa968b2779be9532a4dad431", size = 175423, upload-time = "2025-03-05T20:01:56.276Z" }, - { url = "https://files.pythonhosted.org/packages/76/70/ba1ad96b07869275ef42e2ce21f07a5b0148936688c2baf7e4a1f60d5058/websockets-15.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:678999709e68425ae2593acf2e3ebcbcf2e69885a5ee78f9eb80e6e371f1bf57", size = 173082, upload-time = "2025-03-05T20:01:57.563Z" }, - { url = "https://files.pythonhosted.org/packages/86/f2/10b55821dd40eb696ce4704a87d57774696f9451108cff0d2824c97e0f97/websockets-15.0.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d50fd1ee42388dcfb2b3676132c78116490976f1300da28eb629272d5d93e905", size = 173330, upload-time = "2025-03-05T20:01:59.063Z" }, - { url = "https://files.pythonhosted.org/packages/a5/90/1c37ae8b8a113d3daf1065222b6af61cc44102da95388ac0018fcb7d93d9/websockets-15.0.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d99e5546bf73dbad5bf3547174cd6cb8ba7273062a23808ffea025ecb1cf8562", size = 182878, upload-time = "2025-03-05T20:02:00.305Z" }, - { url = "https://files.pythonhosted.org/packages/8e/8d/96e8e288b2a41dffafb78e8904ea7367ee4f891dafc2ab8d87e2124cb3d3/websockets-15.0.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:66dd88c918e3287efc22409d426c8f729688d89a0c587c88971a0faa2c2f3792", size = 181883, upload-time = "2025-03-05T20:02:03.148Z" }, - { url = "https://files.pythonhosted.org/packages/93/1f/5d6dbf551766308f6f50f8baf8e9860be6182911e8106da7a7f73785f4c4/websockets-15.0.1-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8dd8327c795b3e3f219760fa603dcae1dcc148172290a8ab15158cf85a953413", size = 182252, upload-time = "2025-03-05T20:02:05.29Z" }, - { url = "https://files.pythonhosted.org/packages/d4/78/2d4fed9123e6620cbf1706c0de8a1632e1a28e7774d94346d7de1bba2ca3/websockets-15.0.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8fdc51055e6ff4adeb88d58a11042ec9a5eae317a0a53d12c062c8a8865909e8", size = 182521, upload-time = "2025-03-05T20:02:07.458Z" }, - { url = "https://files.pythonhosted.org/packages/e7/3b/66d4c1b444dd1a9823c4a81f50231b921bab54eee2f69e70319b4e21f1ca/websockets-15.0.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:693f0192126df6c2327cce3baa7c06f2a117575e32ab2308f7f8216c29d9e2e3", size = 181958, upload-time = "2025-03-05T20:02:09.842Z" }, - { url = "https://files.pythonhosted.org/packages/08/ff/e9eed2ee5fed6f76fdd6032ca5cd38c57ca9661430bb3d5fb2872dc8703c/websockets-15.0.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:54479983bd5fb469c38f2f5c7e3a24f9a4e70594cd68cd1fa6b9340dadaff7cf", size = 181918, upload-time = "2025-03-05T20:02:11.968Z" }, - { url = "https://files.pythonhosted.org/packages/d8/75/994634a49b7e12532be6a42103597b71098fd25900f7437d6055ed39930a/websockets-15.0.1-cp311-cp311-win32.whl", hash = "sha256:16b6c1b3e57799b9d38427dda63edcbe4926352c47cf88588c0be4ace18dac85", size = 176388, upload-time = "2025-03-05T20:02:13.32Z" }, - { url = "https://files.pythonhosted.org/packages/98/93/e36c73f78400a65f5e236cd376713c34182e6663f6889cd45a4a04d8f203/websockets-15.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:27ccee0071a0e75d22cb35849b1db43f2ecd3e161041ac1ee9d2352ddf72f065", size = 176828, upload-time = "2025-03-05T20:02:14.585Z" }, { url = "https://files.pythonhosted.org/packages/51/6b/4545a0d843594f5d0771e86463606a3988b5a09ca5123136f8a76580dd63/websockets-15.0.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:3e90baa811a5d73f3ca0bcbf32064d663ed81318ab225ee4f427ad4e26e5aff3", size = 175437, upload-time = "2025-03-05T20:02:16.706Z" }, { url = "https://files.pythonhosted.org/packages/f4/71/809a0f5f6a06522af902e0f2ea2757f71ead94610010cf570ab5c98e99ed/websockets-15.0.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:592f1a9fe869c778694f0aa806ba0374e97648ab57936f092fd9d87f8bc03665", size = 173096, upload-time = "2025-03-05T20:02:18.832Z" }, { url = "https://files.pythonhosted.org/packages/3d/69/1a681dd6f02180916f116894181eab8b2e25b31e484c5d0eae637ec01f7c/websockets-15.0.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0701bc3cfcb9164d04a14b149fd74be7347a530ad3bbf15ab2c678a2cd3dd9a2", size = 173332, upload-time = "2025-03-05T20:02:20.187Z" }, @@ -2500,21 +2289,6 @@ version = "3.5.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/00/5e/d6e5258d69df8b4ed8c83b6664f2b47d30d2dec551a29ad72a6c69eafd31/xxhash-3.5.0.tar.gz", hash = "sha256:84f2caddf951c9cbf8dc2e22a89d4ccf5d86391ac6418fe81e3c67d0cf60b45f", size = 84241, upload-time = "2024-08-17T09:20:38.972Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b8/c7/afed0f131fbda960ff15eee7f304fa0eeb2d58770fade99897984852ef23/xxhash-3.5.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:02c2e816896dc6f85922ced60097bcf6f008dedfc5073dcba32f9c8dd786f3c1", size = 31969, upload-time = "2024-08-17T09:18:00.852Z" }, - { url = "https://files.pythonhosted.org/packages/8c/0c/7c3bc6d87e5235672fcc2fb42fd5ad79fe1033925f71bf549ee068c7d1ca/xxhash-3.5.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:6027dcd885e21581e46d3c7f682cfb2b870942feeed58a21c29583512c3f09f8", size = 30800, upload-time = "2024-08-17T09:18:01.863Z" }, - { url = "https://files.pythonhosted.org/packages/04/9e/01067981d98069eec1c20201f8c145367698e9056f8bc295346e4ea32dd1/xxhash-3.5.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1308fa542bbdbf2fa85e9e66b1077eea3a88bef38ee8a06270b4298a7a62a166", size = 221566, upload-time = "2024-08-17T09:18:03.461Z" }, - { url = "https://files.pythonhosted.org/packages/d4/09/d4996de4059c3ce5342b6e1e6a77c9d6c91acce31f6ed979891872dd162b/xxhash-3.5.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c28b2fdcee797e1c1961cd3bcd3d545cab22ad202c846235197935e1df2f8ef7", size = 201214, upload-time = "2024-08-17T09:18:05.616Z" }, - { url = "https://files.pythonhosted.org/packages/62/f5/6d2dc9f8d55a7ce0f5e7bfef916e67536f01b85d32a9fbf137d4cadbee38/xxhash-3.5.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:924361811732ddad75ff23e90efd9ccfda4f664132feecb90895bade6a1b4623", size = 429433, upload-time = "2024-08-17T09:18:06.957Z" }, - { url = "https://files.pythonhosted.org/packages/d9/72/9256303f10e41ab004799a4aa74b80b3c5977d6383ae4550548b24bd1971/xxhash-3.5.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:89997aa1c4b6a5b1e5b588979d1da048a3c6f15e55c11d117a56b75c84531f5a", size = 194822, upload-time = "2024-08-17T09:18:08.331Z" }, - { url = "https://files.pythonhosted.org/packages/34/92/1a3a29acd08248a34b0e6a94f4e0ed9b8379a4ff471f1668e4dce7bdbaa8/xxhash-3.5.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:685c4f4e8c59837de103344eb1c8a3851f670309eb5c361f746805c5471b8c88", size = 208538, upload-time = "2024-08-17T09:18:10.332Z" }, - { url = "https://files.pythonhosted.org/packages/53/ad/7fa1a109663366de42f724a1cdb8e796a260dbac45047bce153bc1e18abf/xxhash-3.5.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:dbd2ecfbfee70bc1a4acb7461fa6af7748ec2ab08ac0fa298f281c51518f982c", size = 216953, upload-time = "2024-08-17T09:18:11.707Z" }, - { url = "https://files.pythonhosted.org/packages/35/02/137300e24203bf2b2a49b48ce898ecce6fd01789c0fcd9c686c0a002d129/xxhash-3.5.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:25b5a51dc3dfb20a10833c8eee25903fd2e14059e9afcd329c9da20609a307b2", size = 203594, upload-time = "2024-08-17T09:18:13.799Z" }, - { url = "https://files.pythonhosted.org/packages/23/03/aeceb273933d7eee248c4322b98b8e971f06cc3880e5f7602c94e5578af5/xxhash-3.5.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:a8fb786fb754ef6ff8c120cb96629fb518f8eb5a61a16aac3a979a9dbd40a084", size = 210971, upload-time = "2024-08-17T09:18:15.824Z" }, - { url = "https://files.pythonhosted.org/packages/e3/64/ed82ec09489474cbb35c716b189ddc1521d8b3de12b1b5ab41ce7f70253c/xxhash-3.5.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:a905ad00ad1e1c34fe4e9d7c1d949ab09c6fa90c919860c1534ff479f40fd12d", size = 415050, upload-time = "2024-08-17T09:18:17.142Z" }, - { url = "https://files.pythonhosted.org/packages/71/43/6db4c02dcb488ad4e03bc86d70506c3d40a384ee73c9b5c93338eb1f3c23/xxhash-3.5.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:963be41bcd49f53af6d795f65c0da9b4cc518c0dd9c47145c98f61cb464f4839", size = 192216, upload-time = "2024-08-17T09:18:18.779Z" }, - { url = "https://files.pythonhosted.org/packages/22/6d/db4abec29e7a567455344433d095fdb39c97db6955bb4a2c432e486b4d28/xxhash-3.5.0-cp311-cp311-win32.whl", hash = "sha256:109b436096d0a2dd039c355fa3414160ec4d843dfecc64a14077332a00aeb7da", size = 30120, upload-time = "2024-08-17T09:18:20.009Z" }, - { url = "https://files.pythonhosted.org/packages/52/1c/fa3b61c0cf03e1da4767213672efe186b1dfa4fc901a4a694fb184a513d1/xxhash-3.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:b702f806693201ad6c0a05ddbbe4c8f359626d0b3305f766077d51388a6bac58", size = 30003, upload-time = "2024-08-17T09:18:21.052Z" }, - { url = "https://files.pythonhosted.org/packages/6b/8e/9e6fc572acf6e1cc7ccb01973c213f895cb8668a9d4c2b58a99350da14b7/xxhash-3.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:c4dcb4120d0cc3cc448624147dba64e9021b278c63e34a38789b688fd0da9bf3", size = 26777, upload-time = "2024-08-17T09:18:22.809Z" }, { url = "https://files.pythonhosted.org/packages/07/0e/1bfce2502c57d7e2e787600b31c83535af83746885aa1a5f153d8c8059d6/xxhash-3.5.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:14470ace8bd3b5d51318782cd94e6f94431974f16cb3b8dc15d52f3b69df8e00", size = 31969, upload-time = "2024-08-17T09:18:24.025Z" }, { url = "https://files.pythonhosted.org/packages/3f/d6/8ca450d6fe5b71ce521b4e5db69622383d039e2b253e9b2f24f93265b52c/xxhash-3.5.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:59aa1203de1cb96dbeab595ded0ad0c0056bb2245ae11fac11c0ceea861382b9", size = 30787, upload-time = "2024-08-17T09:18:25.318Z" }, { url = "https://files.pythonhosted.org/packages/5b/84/de7c89bc6ef63d750159086a6ada6416cc4349eab23f76ab870407178b93/xxhash-3.5.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:08424f6648526076e28fae6ea2806c0a7d504b9ef05ae61d196d571e5c879c84", size = 220959, upload-time = "2024-08-17T09:18:26.518Z" }, @@ -2553,23 +2327,6 @@ version = "0.24.0" source = { registry = "https://pypi.org/simple" } sdist = { url = "https://files.pythonhosted.org/packages/09/1b/c20b2ef1d987627765dcd5bf1dadb8ef6564f00a87972635099bb76b7a05/zstandard-0.24.0.tar.gz", hash = "sha256:fe3198b81c00032326342d973e526803f183f97aa9e9a98e3f897ebafe21178f", size = 905681, upload-time = "2025-08-17T18:36:36.352Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/01/1f/5c72806f76043c0ef9191a2b65281dacdf3b65b0828eb13bb2c987c4fb90/zstandard-0.24.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:addfc23e3bd5f4b6787b9ca95b2d09a1a67ad5a3c318daaa783ff90b2d3a366e", size = 795228, upload-time = "2025-08-17T18:21:46.978Z" }, - { url = "https://files.pythonhosted.org/packages/0b/ba/3059bd5cd834666a789251d14417621b5c61233bd46e7d9023ea8bc1043a/zstandard-0.24.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:6b005bcee4be9c3984b355336283afe77b2defa76ed6b89332eced7b6fa68b68", size = 640520, upload-time = "2025-08-17T18:21:48.162Z" }, - { url = "https://files.pythonhosted.org/packages/57/07/f0e632bf783f915c1fdd0bf68614c4764cae9dd46ba32cbae4dd659592c3/zstandard-0.24.0-cp311-cp311-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:3f96a9130171e01dbb6c3d4d9925d604e2131a97f540e223b88ba45daf56d6fb", size = 5347682, upload-time = "2025-08-17T18:21:50.266Z" }, - { url = "https://files.pythonhosted.org/packages/a6/4c/63523169fe84773a7462cd090b0989cb7c7a7f2a8b0a5fbf00009ba7d74d/zstandard-0.24.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cd0d3d16e63873253bad22b413ec679cf6586e51b5772eb10733899832efec42", size = 5057650, upload-time = "2025-08-17T18:21:52.634Z" }, - { url = "https://files.pythonhosted.org/packages/c6/16/49013f7ef80293f5cebf4c4229535a9f4c9416bbfd238560edc579815dbe/zstandard-0.24.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:b7a8c30d9bf4bd5e4dcfe26900bef0fcd9749acde45cdf0b3c89e2052fda9a13", size = 5404893, upload-time = "2025-08-17T18:21:54.54Z" }, - { url = "https://files.pythonhosted.org/packages/4d/38/78e8bcb5fc32a63b055f2b99e0be49b506f2351d0180173674f516cf8a7a/zstandard-0.24.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:52cd7d9fa0a115c9446abb79b06a47171b7d916c35c10e0c3aa6f01d57561382", size = 5452389, upload-time = "2025-08-17T18:21:56.822Z" }, - { url = "https://files.pythonhosted.org/packages/55/8a/81671f05619edbacd49bd84ce6899a09fc8299be20c09ae92f6618ccb92d/zstandard-0.24.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a0f6fc2ea6e07e20df48752e7700e02e1892c61f9a6bfbacaf2c5b24d5ad504b", size = 5558888, upload-time = "2025-08-17T18:21:58.68Z" }, - { url = "https://files.pythonhosted.org/packages/49/cc/e83feb2d7d22d1f88434defbaeb6e5e91f42a4f607b5d4d2d58912b69d67/zstandard-0.24.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:e46eb6702691b24ddb3e31e88b4a499e31506991db3d3724a85bd1c5fc3cfe4e", size = 5048038, upload-time = "2025-08-17T18:22:00.642Z" }, - { url = "https://files.pythonhosted.org/packages/08/c3/7a5c57ff49ef8943877f85c23368c104c2aea510abb339a2dc31ad0a27c3/zstandard-0.24.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:d5e3b9310fd7f0d12edc75532cd9a56da6293840c84da90070d692e0bb15f186", size = 5573833, upload-time = "2025-08-17T18:22:02.402Z" }, - { url = "https://files.pythonhosted.org/packages/f9/00/64519983cd92535ba4bdd4ac26ac52db00040a52d6c4efb8d1764abcc343/zstandard-0.24.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:76cdfe7f920738ea871f035568f82bad3328cbc8d98f1f6988264096b5264efd", size = 4961072, upload-time = "2025-08-17T18:22:04.384Z" }, - { url = "https://files.pythonhosted.org/packages/72/ab/3a08a43067387d22994fc87c3113636aa34ccd2914a4d2d188ce365c5d85/zstandard-0.24.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:3f2fe35ec84908dddf0fbf66b35d7c2878dbe349552dd52e005c755d3493d61c", size = 5268462, upload-time = "2025-08-17T18:22:06.095Z" }, - { url = "https://files.pythonhosted.org/packages/49/cf/2abb3a1ad85aebe18c53e7eca73223f1546ddfa3bf4d2fb83fc5a064c5ca/zstandard-0.24.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:aa705beb74ab116563f4ce784fa94771f230c05d09ab5de9c397793e725bb1db", size = 5443319, upload-time = "2025-08-17T18:22:08.572Z" }, - { url = "https://files.pythonhosted.org/packages/40/42/0dd59fc2f68f1664cda11c3b26abdf987f4e57cb6b6b0f329520cd074552/zstandard-0.24.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:aadf32c389bb7f02b8ec5c243c38302b92c006da565e120dfcb7bf0378f4f848", size = 5822355, upload-time = "2025-08-17T18:22:10.537Z" }, - { url = "https://files.pythonhosted.org/packages/99/c0/ea4e640fd4f7d58d6f87a1e7aca11fb886ac24db277fbbb879336c912f63/zstandard-0.24.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e40cd0fc734aa1d4bd0e7ad102fd2a1aefa50ce9ef570005ffc2273c5442ddc3", size = 5365257, upload-time = "2025-08-17T18:22:13.159Z" }, - { url = "https://files.pythonhosted.org/packages/27/a9/92da42a5c4e7e4003271f2e1f0efd1f37cfd565d763ad3604e9597980a1c/zstandard-0.24.0-cp311-cp311-win32.whl", hash = "sha256:cda61c46343809ecda43dc620d1333dd7433a25d0a252f2dcc7667f6331c7b61", size = 435559, upload-time = "2025-08-17T18:22:17.29Z" }, - { url = "https://files.pythonhosted.org/packages/e2/8e/2c8e5c681ae4937c007938f954a060fa7c74f36273b289cabdb5ef0e9a7e/zstandard-0.24.0-cp311-cp311-win_amd64.whl", hash = "sha256:3b95fc06489aa9388400d1aab01a83652bc040c9c087bd732eb214909d7fb0dd", size = 505070, upload-time = "2025-08-17T18:22:14.808Z" }, - { url = "https://files.pythonhosted.org/packages/52/10/a2f27a66bec75e236b575c9f7b0d7d37004a03aa2dcde8e2decbe9ed7b4d/zstandard-0.24.0-cp311-cp311-win_arm64.whl", hash = "sha256:ad9fd176ff6800a0cf52bcf59c71e5de4fa25bf3ba62b58800e0f84885344d34", size = 461507, upload-time = "2025-08-17T18:22:15.964Z" }, { url = "https://files.pythonhosted.org/packages/26/e9/0bd281d9154bba7fc421a291e263911e1d69d6951aa80955b992a48289f6/zstandard-0.24.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:a2bda8f2790add22773ee7a4e43c90ea05598bffc94c21c40ae0a9000b0133c3", size = 795710, upload-time = "2025-08-17T18:22:19.189Z" }, { url = "https://files.pythonhosted.org/packages/36/26/b250a2eef515caf492e2d86732e75240cdac9d92b04383722b9753590c36/zstandard-0.24.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:cc76de75300f65b8eb574d855c12518dc25a075dadb41dd18f6322bda3fe15d5", size = 640336, upload-time = "2025-08-17T18:22:20.466Z" }, { url = "https://files.pythonhosted.org/packages/79/bf/3ba6b522306d9bf097aac8547556b98a4f753dc807a170becaf30dcd6f01/zstandard-0.24.0-cp312-cp312-manylinux2010_i686.manylinux2014_i686.manylinux_2_12_i686.manylinux_2_17_i686.whl", hash = "sha256:d2b3b4bda1a025b10fe0269369475f420177f2cb06e0f9d32c95b4873c9f80b8", size = 5342533, upload-time = "2025-08-17T18:22:22.326Z" },