同步完整源码 - 2026-05-25
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
fly.toml
|
||||
.pytest_cache
|
||||
.github
|
||||
@@ -0,0 +1,26 @@
|
||||
# To run this Dockerfile, do so from the repository root directory
|
||||
# docker build -f api/Dockerfile -t agentops-api .
|
||||
|
||||
FROM python:3.12-slim-bookworm
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
build-essential \
|
||||
git \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/
|
||||
|
||||
COPY api/pyproject.toml /app/
|
||||
|
||||
COPY api/agentops /app/agentops
|
||||
COPY deploy/jockey /app/jockey
|
||||
|
||||
RUN uv sync
|
||||
|
||||
EXPOSE 8000
|
||||
CMD ["uv", "run", "uvicorn", "agentops.app:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -0,0 +1,319 @@
|
||||
# AgentOps Next API Server
|
||||
|
||||
> **Note:** This project uses shared development configurations (linting, formatting) defined in the repository root. Please see the [root README.md](../../README.md#development-setup) for initial setup instructions and tooling details (Ruff).
|
||||
|
||||
## Authentication
|
||||
|
||||
Requests to protected endpoints (primarily `/opsboard/*` and `/v4/*`) require a valid Supabase JWT passed in the `Authorization: Bearer <token>` header. The API server validates this token using the `Depends(get_current_user)` dependency before processing the request.
|
||||
|
||||
## Billing & Subscription Management 💳
|
||||
|
||||
The API server integrates with Stripe to handle subscription billing, payment processing, and organization upgrades. This section covers the billing architecture, setup requirements, and available endpoints.
|
||||
|
||||
### Billing Architecture
|
||||
|
||||
The billing system follows this flow:
|
||||
1. **Frontend** initiates billing actions (upgrade, cancel, reactivate) via API calls
|
||||
2. **API Server** creates Stripe checkout sessions and manages subscription state
|
||||
3. **Stripe Webhooks** notify the API of payment events and subscription changes
|
||||
4. **Database** stores subscription status and organization premium status
|
||||
|
||||
### Stripe Integration Setup
|
||||
|
||||
#### Required Environment Variables
|
||||
|
||||
```bash
|
||||
# Stripe API Configuration
|
||||
STRIPE_SECRET_KEY=sk_test_... # or sk_live_... for production
|
||||
STRIPE_WEBHOOK_SECRET=whsec_... # Webhook signing secret
|
||||
STRIPE_SUBSCRIPTION_PRICE_ID=price_... # Your subscription plan price ID
|
||||
APP_URL=http://localhost:3000 # Frontend URL for redirects
|
||||
```
|
||||
|
||||
#### Webhook Configuration
|
||||
|
||||
Configure a Stripe webhook endpoint pointing to your API server:
|
||||
|
||||
**Production:**
|
||||
- Endpoint URL: `https://your-api-domain.com/v4/stripe-webhook`
|
||||
- Events to send: `checkout.session.completed`, `customer.subscription.updated`, `customer.subscription.deleted`, `charge.dispute.created`
|
||||
|
||||
**Local Development:**
|
||||
Use the Stripe CLI to forward webhooks to your local server:
|
||||
```bash
|
||||
stripe listen --forward-to http://localhost:8000/v4/stripe-webhook
|
||||
```
|
||||
|
||||
### Billing Endpoints
|
||||
|
||||
#### Organization Billing (`/opsboard/orgs/{org_id}/`)
|
||||
|
||||
- **`POST /create-checkout-session`**: Create a Stripe Checkout Session for upgrading to Pro
|
||||
- **Body**: `{ "price_id": "price_...", "discount_code": "optional_code" }`
|
||||
- **Returns**: `{ "clientSecret": "cs_..." }` for Stripe Elements
|
||||
- **Features**:
|
||||
- Double-payment prevention (checks existing active subscriptions)
|
||||
- Discount code validation (promotion codes and coupons)
|
||||
- Idempotency keys for retry safety
|
||||
|
||||
- **`POST /cancel-subscription`**: Cancel an active subscription
|
||||
- **Body**: `{ "subscription_id": "sub_..." }`
|
||||
- **Action**: Sets `cancel_at_period_end=true` (subscription remains active until period end)
|
||||
- **Features**: Idempotency protection, validation checks
|
||||
|
||||
- **`POST /reactivate-subscription`**: Reactivate a cancelled subscription
|
||||
- **Action**: Sets `cancel_at_period_end=false` (continues billing)
|
||||
- **Features**: Idempotency protection, state validation
|
||||
|
||||
- **`POST /validate-discount-code`**: Validate promotion codes before checkout
|
||||
- **Body**: `{ "discount_code": "PROMO20" }`
|
||||
- **Returns**: Discount details and validity status
|
||||
|
||||
#### Webhook Handling (`/v4/stripe-webhook`)
|
||||
|
||||
The webhook endpoint processes these Stripe events:
|
||||
|
||||
- **`checkout.session.completed`**: Updates organization to Pro status after successful payment
|
||||
- **`customer.subscription.updated`**: Handles subscription status changes (active, past_due, etc.)
|
||||
- **`customer.subscription.deleted`**: Downgrades organization to free tier
|
||||
- **`charge.dispute.created`**: Handles payment disputes and chargebacks
|
||||
|
||||
### Billing Data Model
|
||||
|
||||
Organizations store billing-related fields:
|
||||
|
||||
```python
|
||||
class OrgModel:
|
||||
prem_status: PremStatus # 'free' or 'pro'
|
||||
subscription_id: str # Stripe subscription ID
|
||||
subscription_end_date: int # Unix timestamp
|
||||
subscription_cancel_at_period_end: bool
|
||||
```
|
||||
|
||||
### Error Handling & Monitoring
|
||||
|
||||
The billing system includes comprehensive error handling:
|
||||
|
||||
- **Structured Logging**: All billing operations log with structured data for monitoring
|
||||
- **Webhook Replay Protection**: Events are processed idempotently
|
||||
- **Database Transaction Safety**: Rollback on failures with detailed error logging
|
||||
- **Stripe API Error Handling**: Graceful handling of Stripe API failures
|
||||
|
||||
### Security Features
|
||||
|
||||
- **Double-Payment Prevention**: Checks for existing active subscriptions before creating checkout sessions
|
||||
- **Idempotency Keys**: All Stripe operations use unique idempotency keys to prevent duplicates
|
||||
- **Webhook Signature Verification**: All webhook events are cryptographically verified
|
||||
- **Permission Validation**: Only org admins/owners can manage billing
|
||||
|
||||
### Testing Billing Features
|
||||
|
||||
For local development:
|
||||
1. Use Stripe test mode keys (`sk_test_...`, `price_test_...`)
|
||||
2. Use test card numbers (e.g., `4242424242424242`)
|
||||
3. Forward webhooks using `stripe listen`
|
||||
4. Monitor webhook events in Stripe Dashboard
|
||||
|
||||
## API Endpoints
|
||||
|
||||
The API is divided into two main sections: `/opsboard` for user, organization, and project management, and `/v4` for trace and metric data retrieval. All endpoints listed below require JWT authentication.
|
||||
|
||||
### OpsBoard (`/opsboard`)
|
||||
|
||||
Handles core entity management.
|
||||
|
||||
* **Users (`/opsboard/users`)**
|
||||
* `GET /me`: Get details of the currently authenticated user.
|
||||
* `PUT /me`: Update details of the currently authenticated user.
|
||||
* `PUT /me/survey-complete`: Mark the authenticated user's survey as complete.
|
||||
* **Projects (`/opsboard/projects`)**
|
||||
* `GET /`: Get all projects the user has access to (excludes Demo Org).
|
||||
* `GET /{project_id}`: Get details for a specific project.
|
||||
* `POST /`: Create a new project (Requires Admin/Owner role in the org).
|
||||
* `PUT /{project_id}`: Update project name or environment (Requires Admin/Owner role in the org).
|
||||
* `DELETE /{project_id}`: Delete a project (Requires Owner role in the org).
|
||||
* `POST /{project_id}/regenerate-key`: Regenerate the API key for a project (Requires Admin/Owner role in the org).
|
||||
* **Organizations (`/opsboard/orgs`)**
|
||||
* `GET /`: Get all organizations the user belongs to (excludes Demo Org).
|
||||
* `GET /invites`: Get pending invitations *for* the authenticated user.
|
||||
* `GET /{org_id}`: Get detailed information for a specific organization, including members.
|
||||
* `POST /`: Create a new organization (user becomes Owner).
|
||||
* `PUT /{org_id}`: Update organization name (Requires Admin/Owner role).
|
||||
* `POST /{org_id}/invite`: Invite a user (by email) to the organization (Requires Admin/Owner role).
|
||||
* `POST /{org_id}/accept-invite`: Accept a pending invitation for the authenticated user.
|
||||
* `POST /{org_id}/remove-member`: Remove a specified user from the organization (Requires Admin/Owner role; cannot remove self or last Owner).
|
||||
* `POST /{org_id}/change-role`: Change the role of a specified member (Requires Admin/Owner role; cannot change self or demote last Owner).
|
||||
* `POST /{org_id}/create-checkout-session`: Create a Stripe Checkout Session for an organization to upgrade their plan.
|
||||
* `POST /{org_id}/cancel-subscription`: Cancel the active Stripe subscription for an organization.
|
||||
|
||||
### V4 (`/v4`)
|
||||
|
||||
Handles trace and metrics data retrieval, primarily sourced from Clickhouse. These endpoints typically require a `project_id` query parameter.
|
||||
|
||||
* **Traces (`/v4/traces`)**
|
||||
* `GET /?project_id=<id>&...`: Get a list of traces for the specified `project_id`. Supports filtering by time range, span name, pagination (`limit`, `offset`), and sorting (`order_by`, `sort_order`).
|
||||
* `GET /{trace_id}?project_id=<id>`: Get detailed information (including spans) for a specific `trace_id` belonging to the specified `project_id`.
|
||||
* **Metrics (`/v4/meterics`)** *(Note: Prefix is intentionally `meterics`)*
|
||||
* `GET /project?project_id=<id>&...`: Get aggregated metrics (span counts, token usage, costs, durations, etc.) for the specified `project_id`. Supports filtering by time range (`start_time`, `end_time`).
|
||||
* **Webhooks (`/v4`)**
|
||||
* `POST /stripe-webhook`: Handles incoming Stripe events (e.g., `checkout.session.completed`, subscription updates) to manage subscription statuses. Requires specific Stripe webhook configuration in your Stripe dashboard to point to this endpoint.
|
||||
|
||||
## Local Development Setup ⚙️
|
||||
|
||||
Install requirements using `uv` (recommended) or `pip`:
|
||||
|
||||
This API server powers the AgentOps dashboard frontend. You'll need to run this server locally to develop or test frontend features that interact with the API.
|
||||
|
||||
### 1. Environment Variables
|
||||
|
||||
First, set up your environment variables. Copy the example file:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Then, **edit `.env`** and fill in the required values. **This step is crucial for both native and Docker setups.**
|
||||
|
||||
#### Required Environment Variables
|
||||
|
||||
The following variables are **required** for the API to function:
|
||||
|
||||
**Supabase Configuration:**
|
||||
```bash
|
||||
SUPABASE_URL="https://your-project-id.supabase.co"
|
||||
SUPABASE_KEY="your-supabase-service-role-key"
|
||||
JWT_SECRET_KEY="your-jwt-secret-key"
|
||||
```
|
||||
|
||||
**ClickHouse Configuration:**
|
||||
```bash
|
||||
CLICKHOUSE_HOST="your-clickhouse-host.com"
|
||||
CLICKHOUSE_USER="default"
|
||||
CLICKHOUSE_PASSWORD="your-clickhouse-password"
|
||||
CLICKHOUSE_DATABASE="otel_2"
|
||||
```
|
||||
|
||||
#### Optional Environment Variables
|
||||
|
||||
**Stripe (for billing features):**
|
||||
```bash
|
||||
STRIPE_SECRET_KEY="sk_test_your_stripe_secret_key"
|
||||
STRIPE_WEBHOOK_SECRET="whsec_your_webhook_secret"
|
||||
STRIPE_SUBSCRIPTION_PRICE_ID="price_your_subscription_price_id"
|
||||
```
|
||||
|
||||
**Monitoring:**
|
||||
```bash
|
||||
SENTRY_DSN="your-sentry-dsn"
|
||||
DEBUG="true" # Set to false in production
|
||||
LOGGING_LEVEL="INFO"
|
||||
```
|
||||
|
||||
See the `.env.example` file for the complete list of available configuration options.
|
||||
|
||||
Key environment variables include:
|
||||
* `SUPABASE_URL`, `SUPABASE_KEY`, `SUPABASE_JWT_SECRET`: For Supabase connection and JWT validation.
|
||||
* `DATABASE_URL`: For direct PostgreSQL connection (used by SQLAlchemy).
|
||||
* `STRIPE_SECRET_KEY`: Your Stripe secret API key.
|
||||
* **Production**: Use your *live* mode secret key (e.g., `sk_live_...`) from the Stripe Dashboard.
|
||||
* **Local/Development**: Use your *test* mode secret key (e.g., `sk_test_...`) from the Stripe Dashboard.
|
||||
* `STRIPE_WEBHOOK_SECRET`: Secret used to verify signatures of incoming webhooks from Stripe.
|
||||
* **Production**: The signing secret for your *production* webhook endpoint, obtained from the Stripe Dashboard when you configure the endpoint.
|
||||
* **Local/Development (using `stripe listen`)**: When using the Stripe CLI command `stripe listen --forward-to <your_local_api_webhook_url>`, the CLI will output a *temporary, local-only* webhook signing secret (e.g., `whsec_...`). You **must** use this specific secret in your local `.env` file for the API server to correctly verify events forwarded by `stripe listen`. This is different from your production webhook secret. If you use just api-build -s and just api run -s it will handle this secret for you, and you MUST delete it from your .env file if you hard coded it in the past.
|
||||
* `STRIPE_SUBSCRIPTION_PRICE_ID`: The specific Stripe Price ID for your primary subscription plan.
|
||||
* **Production**: The ID of your *live* mode price (e.g., `price_...`) from the Stripe Dashboard.
|
||||
* **Local/Development**: The ID of your *test* mode price (e.g., `price_...`) from the Stripe Dashboard, used for testing subscriptions.
|
||||
* `APP_URL`: The base URL of your frontend application (e.g., `http://localhost:3000`), used for constructing return URLs for Stripe.
|
||||
* `SQLALCHEMY_LOG_LEVEL`: (Optional) Set the logging level for SQLAlchemy. Can be "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL". Defaults to "INFO".
|
||||
* `DEBUG`: Set to `true` for detailed request logging.
|
||||
* `PROFILING_ENABLED`, `PROFILE_OUTPUT_DIR`, `PROFILING_FORMAT`: For request profiling.
|
||||
|
||||
### 2. Choose Your Setup Method:
|
||||
|
||||
#### Option A: Running Natively (Python) 🐍
|
||||
|
||||
Use this method if you want to run the server directly using your local Python environment.
|
||||
|
||||
1. **Install Dependencies:**
|
||||
Use `uv` (recommended) or `pip`:
|
||||
|
||||
```bash
|
||||
# Using uv (faster):
|
||||
uv pip install -r requirements.txt
|
||||
|
||||
# Or using pip:
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
2. **Run the Server:**
|
||||
|
||||
```bash
|
||||
python run.py
|
||||
```
|
||||
|
||||
The API should now be running, typically at `http://localhost:8000`.
|
||||
|
||||
#### Option B: Running with Docker 🐳
|
||||
|
||||
Use this method if you prefer using containers to manage dependencies and the runtime environment.
|
||||
|
||||
1. **Build the Docker Image:**
|
||||
Make sure you're in the `api/` directory.
|
||||
|
||||
```bash
|
||||
docker build -t agentops-api .
|
||||
```
|
||||
|
||||
2. **Run the Docker Container:**
|
||||
This command maps port 8000, loads environment variables from your `.env` file (make sure you completed Step 1!), automatically removes the container on exit (`--rm`), and names the container.
|
||||
|
||||
```bash
|
||||
docker run -p 8000:8000 --env-file .env --rm --name agentops-api-container agentops-api
|
||||
```
|
||||
|
||||
The API should now be accessible at `http://localhost:8000`! 🎉
|
||||
|
||||
## Request Logging
|
||||
|
||||
The API logs basic information about all requests by default. To enable detailed request body logging, set the `DEBUG` environment variable to `true`:
|
||||
|
||||
```bash
|
||||
# In your .env file
|
||||
DEBUG=true
|
||||
```
|
||||
|
||||
This will log the full request body for all POST, PUT, and PATCH requests, which is useful for debugging but may contain sensitive information.
|
||||
|
||||
## Profiling
|
||||
|
||||
The API includes request profiling functionality using [pyinstrument](https://github.com/joerick/pyinstrument).
|
||||
|
||||
### Setup
|
||||
|
||||
1. Enable profiling by setting the environment variable in your .env file:
|
||||
|
||||
```
|
||||
PROFILING_ENABLED=true
|
||||
```
|
||||
|
||||
2. Optionally, set a custom output directory for profile files:
|
||||
|
||||
```
|
||||
PROFILE_OUTPUT_DIR=/path/to/profiles
|
||||
```
|
||||
|
||||
3. Choose between HTML or Speedscope profiles:
|
||||
```
|
||||
PROFILING_FORMAT=html # default
|
||||
```
|
||||
or
|
||||
```
|
||||
PROFILING_FORMAT=speedscope
|
||||
```
|
||||
|
||||
Profile files are saved to the current directory or the configured `PROFILE_OUTPUT_DIR` with a timestamp in the filename.
|
||||
|
||||
### Viewing Profiles
|
||||
|
||||
- Speedscope profiles (.speedscope.json): Upload to [speedscope.app](https://www.speedscope.app/)
|
||||
- HTML profiles (.html): Open in any browser
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"folders": [
|
||||
{
|
||||
"path": "../../../agentops"
|
||||
},
|
||||
{
|
||||
"path": "../.."
|
||||
},
|
||||
{
|
||||
"path": "../../../agentops-ts"
|
||||
}
|
||||
],
|
||||
"settings": {},
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import fastapi
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from agentops.common.middleware import (
|
||||
CacheControlMiddleware,
|
||||
ExceptionMiddleware,
|
||||
DefaultContentTypeMiddleware,
|
||||
)
|
||||
from agentops.api.routes import v1, v2, v3, v4
|
||||
|
||||
|
||||
app = fastapi.FastAPI(
|
||||
docs_url=None, # Disable docs in the mounted app to avoid conflicts
|
||||
openapi_url=None, # Disable OpenAPI in the mounted app to avoid conflicts
|
||||
title="AgentOps API",
|
||||
description="AgentOps API for managing sessions, agents, and events",
|
||||
)
|
||||
|
||||
# A number of routes inside this app need to have alow_origins set to all, since they
|
||||
# communicate with the SDK from client machines directly. Traces and Meterics routes
|
||||
# should be behind CORS protection, and since they use a cookie for auth, they
|
||||
# theoretically should require that the origins be restricted, but in practice this
|
||||
# seems to work.
|
||||
# We use a decorator to explicitly add CORS headers to the routes that need it.
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=['*'],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"], # Allow all methods
|
||||
allow_headers=["*"], # Allow all headers
|
||||
)
|
||||
|
||||
app.add_middleware(CacheControlMiddleware)
|
||||
app.add_middleware(ExceptionMiddleware)
|
||||
app.add_middleware(DefaultContentTypeMiddleware)
|
||||
|
||||
# Include routers
|
||||
app.include_router(v1.router)
|
||||
app.include_router(v2.router)
|
||||
app.include_router(v3.router)
|
||||
app.include_router(v4.router)
|
||||
|
||||
|
||||
# Health Check
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return {"message": "Server Up"}
|
||||
@@ -0,0 +1,156 @@
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import jwt
|
||||
from fastapi import Header, HTTPException
|
||||
|
||||
from agentops.api.environment import JWT_SECRET_KEY
|
||||
from agentops.opsboard.models import ProjectModel
|
||||
|
||||
|
||||
JWT_EXPIRATION_DAYS: int = 30
|
||||
JWT_ALGO: str = "HS256"
|
||||
|
||||
|
||||
def _generate_jwt_timestamp() -> int:
|
||||
"""Generate a timestamp for the JWT token expiration."""
|
||||
return int((datetime.now() + timedelta(days=JWT_EXPIRATION_DAYS)).timestamp())
|
||||
|
||||
|
||||
def _assert_jwt_secret() -> None:
|
||||
"""Assert that the JWT secret key is set in the environment."""
|
||||
if not JWT_SECRET_KEY:
|
||||
raise HTTPException(status_code=500, detail="JWT secret not configured")
|
||||
|
||||
|
||||
@dataclass
|
||||
class JWTPayload:
|
||||
"""
|
||||
Dataclass to represent the payload of a JWT token.
|
||||
This is used for type checking and validation of the JWT payload.
|
||||
"""
|
||||
|
||||
exp: int
|
||||
aud: str
|
||||
project_id: str
|
||||
project_prem_status: str
|
||||
api_key: str
|
||||
dev: bool = False
|
||||
|
||||
def asdict(self) -> dict:
|
||||
"""Convert the payload to a dictionary format."""
|
||||
properties = {
|
||||
"exp": self.exp,
|
||||
"aud": self.aud,
|
||||
"project_id": self.project_id,
|
||||
"project_prem_status": self.project_prem_status,
|
||||
"api_key": self.api_key,
|
||||
}
|
||||
|
||||
if self.dev:
|
||||
properties["dev"] = self.dev
|
||||
|
||||
return properties
|
||||
|
||||
@classmethod
|
||||
def from_project(cls, project: ProjectModel, dev: bool = False) -> "JWTPayload":
|
||||
"""
|
||||
Create a new instance of JWTPayload with the given project_id and role.
|
||||
The expiration time is set to 30 days from now.
|
||||
"""
|
||||
return cls(
|
||||
exp=_generate_jwt_timestamp(),
|
||||
aud="authenticated",
|
||||
project_id=str(project.id),
|
||||
project_prem_status=project.org.prem_status.value,
|
||||
api_key=str(project.api_key),
|
||||
dev=dev,
|
||||
)
|
||||
|
||||
|
||||
def generate_jwt(project: ProjectModel) -> str:
|
||||
"""Generate a JWT token for a project"""
|
||||
_assert_jwt_secret()
|
||||
|
||||
payload = JWTPayload.from_project(project)
|
||||
return jwt.encode(
|
||||
payload.asdict(),
|
||||
JWT_SECRET_KEY,
|
||||
algorithm=JWT_ALGO,
|
||||
)
|
||||
|
||||
|
||||
def verify_jwt(token: str) -> JWTPayload:
|
||||
"""Verify a JWT token"""
|
||||
_assert_jwt_secret()
|
||||
|
||||
payload_data = jwt.decode(
|
||||
token,
|
||||
JWT_SECRET_KEY,
|
||||
algorithms=[JWT_ALGO],
|
||||
audience="authenticated", # Verify audience claim
|
||||
)
|
||||
return JWTPayload(**payload_data)
|
||||
|
||||
|
||||
async def get_jwt_token(authorization: str = Header(None)) -> JWTPayload:
|
||||
"""
|
||||
Dependency to extract and verify JWT token from Authorization header
|
||||
|
||||
Usage:
|
||||
- Include this as a dependency in route functions
|
||||
- The JWT payload will be passed to the route function
|
||||
"""
|
||||
if not authorization:
|
||||
raise HTTPException(status_code=401, detail="Authorization header missing")
|
||||
|
||||
try:
|
||||
# Extract token from "Bearer <token>" format
|
||||
scheme, token = authorization.split()
|
||||
if scheme.lower() != "bearer":
|
||||
raise HTTPException(status_code=401, detail="Invalid authentication scheme")
|
||||
|
||||
return verify_jwt(token)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=401, detail="Invalid token format")
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise HTTPException(status_code=401, detail="Token has expired")
|
||||
except jwt.InvalidAudienceError:
|
||||
raise HTTPException(status_code=401, detail="Invalid audience")
|
||||
except jwt.InvalidTokenError:
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
|
||||
|
||||
def generate_dev_token(project_id: str) -> str:
|
||||
"""
|
||||
Generate a development JWT token for testing with a specific project ID.
|
||||
This should only be used for development/testing purposes.
|
||||
|
||||
Args:
|
||||
project_id: The project ID to include in the token
|
||||
|
||||
Returns:
|
||||
str: The generated JWT token
|
||||
|
||||
Raises:
|
||||
ValueError: If JWT secret is not configured
|
||||
"""
|
||||
if not JWT_SECRET_KEY:
|
||||
raise ValueError("JWT_SECRET_KEY environment variable is not set")
|
||||
|
||||
# Create a JWT payload for development purposes
|
||||
payload = JWTPayload(
|
||||
exp=_generate_jwt_timestamp(),
|
||||
aud="authenticated",
|
||||
project_id=project_id,
|
||||
project_prem_status="premium", # Default to premium for dev tokens
|
||||
api_key="dev-token", # Placeholder API key for dev tokens
|
||||
dev=True, # Mark as development token
|
||||
)
|
||||
|
||||
# Encode the payload
|
||||
return jwt.encode(
|
||||
payload.asdict(),
|
||||
JWT_SECRET_KEY,
|
||||
algorithm=JWT_ALGO,
|
||||
)
|
||||
@@ -0,0 +1,469 @@
|
||||
import asyncio
|
||||
from typing import TypeVar, ClassVar, Type, Any, Optional, Union, Collection, Tuple, Literal
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
import abc
|
||||
import pydantic
|
||||
from clickhouse_connect.driver.asyncclient import AsyncClient
|
||||
from agentops.api.db.clickhouse_client import get_async_clickhouse # type: ignore
|
||||
|
||||
|
||||
TOperation = TypeVar('TOperation', bound='BaseOperation')
|
||||
TClickhouseModel = TypeVar('TClickhouseModel', bound='ClickhouseModel')
|
||||
TClickhouseAggregatedModel = TypeVar('TClickhouseAggregatedModel', bound='ClickhouseAggregatedModel')
|
||||
|
||||
# Defines the filterable fields on a Model.
|
||||
FilterDict = dict[str, Tuple[Union[str, Type[TOperation]], str]] # {field_name: (operator, db_column)}
|
||||
|
||||
# Types that can be automatically formatted for ClickHouse queries
|
||||
FormattableValue = Union[datetime, UUID, str, int, float, bool, None]
|
||||
|
||||
# FilterFields is a dictionary of field names to values that can be used in WHERE clauses
|
||||
FilterFields = dict[str, FormattableValue] # Filter values for queries
|
||||
|
||||
# SelectFields can be a string (like "*"), a list of field names, or a dict mapping
|
||||
SelectFields = Union[str, Collection[str], dict[str, str]]
|
||||
|
||||
# Fields that can be searched with LIKE/ILIKE pattern matching
|
||||
SearchFields = dict[str, Tuple[Literal["LIKE", "ILIKE"], str]] # {field_name: (operator, db_column)}
|
||||
# Search term is simply a string that gets applied to all configured searchable fields
|
||||
|
||||
__all__ = [
|
||||
'ClickhouseModel',
|
||||
'TClickhouseModel',
|
||||
'ClickhouseAggregatedModel',
|
||||
'TClickhouseAggregatedModel',
|
||||
'FilterDict',
|
||||
'FilterFields',
|
||||
'FormattableValue',
|
||||
'SelectFields',
|
||||
'SearchFields',
|
||||
]
|
||||
|
||||
|
||||
def _format_field_value(value: FormattableValue) -> Any:
|
||||
"""
|
||||
Format field values for ClickHouse queries based on their type.
|
||||
|
||||
This method provides a centralized place to handle type conversions
|
||||
for different Python types to their ClickHouse-compatible formats.
|
||||
|
||||
Args:
|
||||
value: The value to format (datetime, UUID, or basic types)
|
||||
|
||||
Returns:
|
||||
The formatted value suitable for ClickHouse queries
|
||||
"""
|
||||
if isinstance(value, datetime):
|
||||
return value.strftime('%Y-%m-%d %H:%M:%S') # ClickHouse format: 'YYYY-MM-DD HH:MM:SS'
|
||||
|
||||
if isinstance(value, UUID):
|
||||
return str(value)
|
||||
|
||||
return value
|
||||
|
||||
|
||||
class BaseOperation(abc.ABC):
|
||||
"""
|
||||
Base class for custom Clickhouse filter operations.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@abc.abstractmethod
|
||||
def format(db_field: str, field: str, value: Any) -> tuple[str, dict]: ...
|
||||
|
||||
|
||||
class WithinListOperation(BaseOperation):
|
||||
"""
|
||||
Operation for filtering within a list of values.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def format(db_field: str, field: str, value: list | tuple) -> tuple[str, dict]:
|
||||
# multiple ORs are faster than a single IN
|
||||
assert isinstance(value, (list, tuple)), f"Expected list or tuple, got {type(value)}"
|
||||
|
||||
params, conditions = {}, []
|
||||
for idx, item in enumerate(value):
|
||||
conditions.append(f"{db_field} = %({field}_withinlist_{idx})s")
|
||||
params[f"{field}_withinlist_{idx}"] = _format_field_value(item)
|
||||
return " OR ".join(conditions), params
|
||||
|
||||
|
||||
class ClickhouseModel(abc.ABC, pydantic.BaseModel):
|
||||
"""Base abstract model for Clickhouse database interactions.
|
||||
|
||||
This model provides a standardized interface for querying Clickhouse tables,
|
||||
with support for filtering, field selection, and result pagination. It handles
|
||||
parameter binding and query generation automatically based on class attributes.
|
||||
|
||||
Configuration:
|
||||
- table_name: The Clickhouse table to query
|
||||
- selectable_fields: Fields to SELECT by default (defaults to "*") This
|
||||
should be populated as a lookup table for conversion os column names
|
||||
to your python attribute names.
|
||||
For example:
|
||||
selectable_fields = {'Timestamp': 'timestamp'} allows you to refer
|
||||
to `timestamp` in your python code.
|
||||
- filterable_fields: Dict mapping Python attribute names to tuples of
|
||||
(comparison_operator, db_column_name).
|
||||
For example:
|
||||
{"project_id": ("=", "ProjectId")} enables filtering by project_id
|
||||
- searchable_fields: Dict mapping Python attribute names to tuples of
|
||||
(search_operator, db_column_name) for string search operations.
|
||||
For example:
|
||||
{"name": ("ILIKE", "UserName")} enables searching by name
|
||||
For models using GROUP BY with HAVING clauses, the db_column_name should
|
||||
reference the column alias created in the query, not the original table column.
|
||||
|
||||
Usage example:
|
||||
```python
|
||||
class UserModel(ClickhouseModel):
|
||||
table_name = "users"
|
||||
selectable_fields = {
|
||||
"Id": "id",
|
||||
"Age": "age",
|
||||
"Timestamp": "timestamp",
|
||||
"ProjectId": "project_id",
|
||||
"UserName": "name",
|
||||
}
|
||||
filterable_fields = {
|
||||
"user_id": ("=", "Id"),
|
||||
"min_age": (">=", "Age"),
|
||||
"max_age": ("<=", "Age"),
|
||||
}
|
||||
searchable_fields = {
|
||||
"name": ("ILIKE", "UserName"),
|
||||
}
|
||||
|
||||
# Get users between ages 18-30
|
||||
users = await UserModel.select(filters={"min_age": 18, "max_age": 30})
|
||||
|
||||
# Search for users with names containing 'john'
|
||||
users = await UserModel.select(search="john")
|
||||
```
|
||||
|
||||
This is intended to be used to query a single table.
|
||||
Override the _get_query method for more complex query customization.
|
||||
See `ClickhouseAggregatedModel` for handling multiple models in a single query.
|
||||
"""
|
||||
|
||||
table_name: ClassVar[Optional[str]] = None
|
||||
selectable_fields: ClassVar[SelectFields] = "*"
|
||||
filterable_fields: ClassVar[FilterDict] = {
|
||||
# field_name: (comparison_operator, db_column_name)
|
||||
"id": ("=", "Id"),
|
||||
"start_time": (">=", "Timestamp"),
|
||||
"end_time": ("<=", "Timestamp"),
|
||||
}
|
||||
searchable_fields: ClassVar[SearchFields] = {
|
||||
# "field_name": ("ILIKE", db_column_name)
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _get_select_clause(cls, *, fields: Optional[SelectFields] = None) -> str:
|
||||
"""
|
||||
Get the selectable fields for the model. This allows subclasses to customize
|
||||
the selectable fields dynamically if needed.
|
||||
Returns:
|
||||
SelectFields: The selectable fields for the model, which can be a string, list, or dict.
|
||||
"""
|
||||
if fields is None:
|
||||
fields = cls.selectable_fields
|
||||
|
||||
if isinstance(fields, str): # str like "*" or a single db column name
|
||||
return fields
|
||||
|
||||
if isinstance(fields, (tuple, list)): # list of field names
|
||||
return ', '.join(fields)
|
||||
|
||||
if isinstance(fields, dict): # dict of field names to db column names
|
||||
return ', '.join([f"{db_col} as {field}" for db_col, field in fields.items()])
|
||||
|
||||
raise ValueError(f"Invalid fields type: {type(fields)}. Expected str, list, tuple, or dict.")
|
||||
|
||||
@classmethod
|
||||
def _get_search_clause(cls, search_term: Optional[str] = None) -> tuple[str, dict]:
|
||||
"""
|
||||
Generate search conditions based on the searchable_fields configuration.
|
||||
|
||||
Arguments:
|
||||
search_term: The search term to apply to all searchable fields
|
||||
|
||||
Returns:
|
||||
tuple[str, dict]: A tuple containing:
|
||||
- clause: The search conditions string (joined with OR), empty string if no conditions
|
||||
- params: Dictionary of parameter values for the conditions
|
||||
"""
|
||||
conditions = []
|
||||
params = {}
|
||||
|
||||
if search_term is not None:
|
||||
for field, (op, db_field) in cls.searchable_fields.items():
|
||||
param_name = f"search_{field}" # avoid collisions with other params
|
||||
conditions.append(f"{db_field} {op} %({param_name})s")
|
||||
params[param_name] = f"%{search_term}%"
|
||||
|
||||
# Join conditions with OR - this is more intuitive for searches across multiple fields
|
||||
# Users expect to see results where ANY field matches, not where ALL fields match
|
||||
return " OR ".join(conditions), params
|
||||
|
||||
@classmethod
|
||||
def _get_where_clause(cls, **filters: FormattableValue) -> tuple[str, dict]:
|
||||
"""
|
||||
Generate the WHERE clause for the SQL query based on the provided filterable fields.
|
||||
|
||||
Arguments:
|
||||
filters: The keyword arguments to filter on. Each key should match a filterable field in the model.
|
||||
|
||||
Returns:
|
||||
tuple[str, dict]: A tuple containing:
|
||||
- clause: The WHERE clause string (joined with AND), empty string if no conditions
|
||||
- params: Dictionary of parameter values for the conditions
|
||||
|
||||
Example:
|
||||
(
|
||||
"ProjectId = %(project_id)s AND Timestamp >= %(start_time)s",
|
||||
{'project_id': 'my_project', 'start_time': '2023-01-01'}
|
||||
)
|
||||
"""
|
||||
conditions = []
|
||||
params = {}
|
||||
|
||||
for field, (op, db_field) in cls.filterable_fields.items():
|
||||
if (value := filters.get(field)) is not None:
|
||||
if isinstance(op, type) and issubclass(op, BaseOperation):
|
||||
# dynamic operation
|
||||
_cond, _params = op.format(db_field, field, value)
|
||||
conditions.append(_cond)
|
||||
params.update(_params)
|
||||
else:
|
||||
# basic operation
|
||||
conditions.append(f"{db_field} {op} %({field})s")
|
||||
params[field] = _format_field_value(value)
|
||||
|
||||
# Join conditions with AND
|
||||
return " AND ".join(conditions), params
|
||||
|
||||
@classmethod
|
||||
def _get_select_query(
|
||||
cls: Type[TClickhouseModel],
|
||||
*,
|
||||
fields: Optional[SelectFields] = None,
|
||||
filters: Optional[FilterFields] = None,
|
||||
search: Optional[str] = None,
|
||||
order_by: Optional[str] = None,
|
||||
offset: Optional[int] = None,
|
||||
limit: Optional[int] = None,
|
||||
) -> tuple[str, dict[str, Any]]:
|
||||
"""Generate SQL query and parameters for this model.
|
||||
|
||||
This internal method builds the SQL query string and parameters dictionary
|
||||
used by the select method. It's commonly overridden by subclasses to
|
||||
customize the query logic or structure.
|
||||
|
||||
Args:
|
||||
fields: Fields to select (defaults to cls.selectable_fields)
|
||||
filters: Filters to apply in the WHERE clause
|
||||
search: Search string to apply to all configured searchable fields
|
||||
order_by: ORDER BY clause (without the "ORDER BY" prefix)
|
||||
offset: OFFSET value for pagination
|
||||
limit: LIMIT value to restrict result count
|
||||
|
||||
Returns:
|
||||
tuple[str, dict]: A tuple containing:
|
||||
- The SQL query string with parameterized values
|
||||
- A dictionary of parameter values for safe query execution
|
||||
"""
|
||||
assert cls.table_name, f"table_name must be set for {cls.__name__} to generate SQL queries"
|
||||
|
||||
select_clause = cls._get_select_clause(fields=fields)
|
||||
filter_clause, filter_params = cls._get_where_clause(**(filters or {}))
|
||||
search_clause, search_params = cls._get_search_clause(search)
|
||||
params = {**filter_params, **search_params}
|
||||
|
||||
if filter_clause and search_clause:
|
||||
where_clause = f"({filter_clause}) AND ({search_clause})"
|
||||
else:
|
||||
where_clause = filter_clause or search_clause
|
||||
|
||||
query = f"""
|
||||
SELECT {select_clause}
|
||||
FROM {cls.table_name}
|
||||
{f"WHERE {where_clause}" if where_clause else ""}
|
||||
"""
|
||||
|
||||
if order_by is not None:
|
||||
query += f" ORDER BY {order_by}"
|
||||
|
||||
if limit is not None:
|
||||
query += f" LIMIT {limit}"
|
||||
|
||||
if offset is not None:
|
||||
query += f" OFFSET {offset}"
|
||||
|
||||
return query, params
|
||||
|
||||
@classmethod
|
||||
async def select(
|
||||
cls: Type[TClickhouseModel],
|
||||
*,
|
||||
fields: Optional[SelectFields] = None,
|
||||
filters: Optional[FilterFields] = None,
|
||||
search: Optional[str] = None,
|
||||
order_by: Optional[str] = None,
|
||||
offset: Optional[int] = None,
|
||||
limit: Optional[int] = None,
|
||||
) -> list[TClickhouseModel]:
|
||||
"""Query the database and return a list of model instances.
|
||||
|
||||
This method builds and executes a SQL query based on the provided parameters and
|
||||
class configuration, then converts the query results into model instances.
|
||||
|
||||
Args:
|
||||
fields: Optional list of fields to select. Defaults to cls.selectable_fields.
|
||||
Example: ["id", "name", "email"]
|
||||
filters: Optional dictionary of filters to apply. Keys must be defined in
|
||||
cls.filterable_fields to be effective.
|
||||
Example: {"project_id": "123", "start_time": "2023-01-01"}
|
||||
search: Optional search string to apply to all searchable fields configured in
|
||||
cls.searchable_fields. For LIKE/ILIKE searches, wildcards (%)
|
||||
are automatically added if not present.
|
||||
Example: "authentication" will search all configured fields for "authentication"
|
||||
order_by: Optional ORDER BY clause (without the "ORDER BY" prefix).
|
||||
Example: "created_at DESC"
|
||||
offset: Optional OFFSET value for pagination.
|
||||
limit: Optional LIMIT value to restrict the number of results.
|
||||
|
||||
Returns:
|
||||
List[TClickhouseModel]: A list of model instances of the exact calling class type,
|
||||
with each instance created from a row in the query results. The return type is
|
||||
properly typed using generics to preserve the concrete subclass type.
|
||||
|
||||
Example:
|
||||
```python
|
||||
# Get last 10 traces for a specific project
|
||||
traces = await TraceModel.select(
|
||||
filters={"project_id": "abc123"},
|
||||
order_by="timestamp DESC",
|
||||
limit=10
|
||||
)
|
||||
|
||||
# Search for traces with spans containing "authentication"
|
||||
traces = await TraceModel.select(
|
||||
filters={"project_id": "abc123"},
|
||||
search="authentication",
|
||||
limit=10
|
||||
)
|
||||
|
||||
# Access model properties on the results
|
||||
for trace in traces:
|
||||
print(f"Trace {trace.trace_id}: {trace.total_tokens} tokens")
|
||||
```
|
||||
"""
|
||||
query, params = cls._get_select_query(
|
||||
fields=fields,
|
||||
filters=filters,
|
||||
search=search,
|
||||
order_by=order_by,
|
||||
offset=offset,
|
||||
limit=limit,
|
||||
)
|
||||
client: AsyncClient = await get_async_clickhouse()
|
||||
result = await client.query(query, parameters=params)
|
||||
results = list(result.named_results())
|
||||
return [cls(**row) for row in results]
|
||||
|
||||
|
||||
class ClickhouseAggregatedModel(abc.ABC, pydantic.BaseModel):
|
||||
"""Base model for composing and executing multiple Clickhouse queries in parallel.
|
||||
|
||||
This model allows you to combine results from multiple ClickhouseModel queries
|
||||
into a single aggregated model. It executes all queries concurrently for better
|
||||
performance and constructs a model instance with the combined results.
|
||||
|
||||
Configuration:
|
||||
- aggregated_models: Class variable listing the ClickhouseModel subclasses to query
|
||||
|
||||
How it works:
|
||||
1. The select() method takes filters that apply to all underlying models
|
||||
2. Queries from each model in aggregated_models are generated and executed in parallel
|
||||
3. Results from each query are passed as positional arguments to the constructor
|
||||
4. The model can then process and combine data from all queries
|
||||
|
||||
This pattern is useful when you need to:
|
||||
- Fetch different types of data in a single request
|
||||
- Create aggregated metrics from multiple tables
|
||||
- Provide a unified API for related data
|
||||
"""
|
||||
|
||||
aggregated_models: ClassVar[Collection[Type[ClickhouseModel]]]
|
||||
|
||||
# TODO this can accept all the other query params, too
|
||||
@classmethod
|
||||
async def select(
|
||||
cls: Type[TClickhouseAggregatedModel],
|
||||
*,
|
||||
fields: Optional[SelectFields] = None,
|
||||
filters: Optional[FilterFields] = None,
|
||||
search: Optional[str] = None,
|
||||
order_by: Optional[str] = None,
|
||||
offset: Optional[int] = None,
|
||||
limit: Optional[int] = None,
|
||||
) -> TClickhouseAggregatedModel:
|
||||
"""Execute parallel queries for all aggregated models and return a combined model.
|
||||
|
||||
This method:
|
||||
1. Generates a query for each model defined in aggregated_models
|
||||
2. Executes all queries concurrently using asyncio.gather
|
||||
3. Processes the results into lists of model instances
|
||||
4. Passes the processed results to the model's constructor
|
||||
|
||||
When passing arguments:
|
||||
It is up to the individual model implementations to accept the arguments
|
||||
in their `select` method and process them accordingly.
|
||||
|
||||
Args:
|
||||
fields: Optional list of fields to select for each aggregated model.
|
||||
filters: Optional dictionary of filters to apply to all aggregated models.
|
||||
This should match the filterable fields in each model.
|
||||
search: Optional search string to apply to all searchable fields
|
||||
configured in each model's searchable_fields.
|
||||
order_by: Optional ORDER BY clause (without the "ORDER BY" prefix) to apply to each query.
|
||||
offset: Optional OFFSET value for pagination (applies to each query).
|
||||
limit: Optional LIMIT value to restrict the number of results for each query.
|
||||
|
||||
Returns:
|
||||
An instance of the calling class, initialized with the results
|
||||
from all the queries. The exact return type depends on the
|
||||
implementation of the subclass's __init__ method. Results are passed
|
||||
as positional arguments corresponding to the order of models in
|
||||
`aggregated_models`.
|
||||
"""
|
||||
assert cls.aggregated_models, f"{cls.__name__} must define `aggregated_models`"
|
||||
|
||||
client: AsyncClient = await get_async_clickhouse()
|
||||
queries: list[str] = []
|
||||
params: list[dict] = []
|
||||
|
||||
for model_cls in cls.aggregated_models:
|
||||
_query, _params = model_cls._get_select_query(
|
||||
fields=fields,
|
||||
filters=filters,
|
||||
search=search,
|
||||
order_by=order_by,
|
||||
offset=offset,
|
||||
limit=limit,
|
||||
)
|
||||
queries.append(_query)
|
||||
params.append(_params)
|
||||
|
||||
responses: list = await asyncio.gather(
|
||||
*[client.query(q, parameters=p) for q, p in zip(queries, params)]
|
||||
)
|
||||
|
||||
results: list = []
|
||||
for response in responses:
|
||||
results.append(list(response.named_results()))
|
||||
|
||||
return cls(*results)
|
||||
@@ -0,0 +1,131 @@
|
||||
import asyncio
|
||||
import threading
|
||||
from typing import Annotated
|
||||
|
||||
from clickhouse_connect import get_async_client, get_client
|
||||
from clickhouse_connect.driver.asyncclient import AsyncClient
|
||||
from clickhouse_connect.driver.client import Client
|
||||
from fastapi import Depends
|
||||
|
||||
from agentops.api.environment import (
|
||||
CLICKHOUSE_DATABASE,
|
||||
CLICKHOUSE_HOST,
|
||||
CLICKHOUSE_PASSWORD,
|
||||
CLICKHOUSE_PORT,
|
||||
CLICKHOUSE_USER,
|
||||
CLICKHOUSE_SECURE,
|
||||
)
|
||||
|
||||
# Global variables to store client instances
|
||||
clickhouse = None
|
||||
async_clickhouse = None
|
||||
|
||||
|
||||
# Create locks for thread-safe initialization
|
||||
_clickhouse_lock = threading.Lock()
|
||||
_async_clickhouse_lock = asyncio.Lock()
|
||||
|
||||
|
||||
class ConnectionConfig:
|
||||
"""
|
||||
Connection configuration for Supabase.
|
||||
|
||||
This is an intermediary because it allows us to easily modify the vars in tests.
|
||||
"""
|
||||
|
||||
host: str = CLICKHOUSE_HOST
|
||||
port: str | int = CLICKHOUSE_PORT
|
||||
database: str = CLICKHOUSE_DATABASE
|
||||
username: str = CLICKHOUSE_USER
|
||||
password: str = CLICKHOUSE_PASSWORD
|
||||
secure: bool = CLICKHOUSE_SECURE
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Non-instantiable class has a lower chance of being printed."""
|
||||
raise NotImplementedError("Cannot instantiate ConnectionConfig.")
|
||||
|
||||
@classmethod
|
||||
def to_connection_dict(cls) -> dict[str, str | int]:
|
||||
"""
|
||||
Convert the connection configuration to a dictionary that can be passed
|
||||
as kwargs to get_client and get_async_client.
|
||||
|
||||
Returns:
|
||||
dict[str, str | int]: The connection configuration as a dictionary.
|
||||
"""
|
||||
return {
|
||||
'host': cls.host,
|
||||
'port': cls.port,
|
||||
'database': cls.database,
|
||||
'username': cls.username,
|
||||
'password': cls.password,
|
||||
'secure': cls.secure,
|
||||
}
|
||||
|
||||
|
||||
def get_clickhouse():
|
||||
"""
|
||||
FastAPI dependency to get the synchronous ClickHouse client.
|
||||
This allows for proper dependency injection and easier testing.
|
||||
|
||||
Returns:
|
||||
Client: The synchronous ClickHouse client instance
|
||||
"""
|
||||
global clickhouse
|
||||
|
||||
if clickhouse is None:
|
||||
with _clickhouse_lock:
|
||||
# Check again inside the lock to prevent race conditions
|
||||
if clickhouse is None:
|
||||
clickhouse = get_client(**ConnectionConfig.to_connection_dict())
|
||||
return clickhouse
|
||||
|
||||
|
||||
async def get_async_clickhouse():
|
||||
"""
|
||||
FastAPI dependency to get the async ClickHouse client.
|
||||
This allows for proper dependency injection and easier testing.
|
||||
|
||||
Returns:
|
||||
AsyncClient: The async ClickHouse client instance
|
||||
"""
|
||||
global async_clickhouse
|
||||
|
||||
# Check again inside the lock to prevent race conditions
|
||||
if async_clickhouse is None:
|
||||
async with _async_clickhouse_lock:
|
||||
# Check again inside the lock to prevent race conditions
|
||||
if async_clickhouse is None:
|
||||
async_clickhouse = await get_async_client(**ConnectionConfig.to_connection_dict())
|
||||
return async_clickhouse
|
||||
|
||||
|
||||
# Annotated dependencies for better type hinting
|
||||
AsyncClickHouseClient = Annotated[AsyncClient, Depends(get_async_clickhouse)]
|
||||
ClickHouseClient = Annotated[Client, Depends(get_clickhouse)]
|
||||
|
||||
|
||||
async def close_clickhouse_clients():
|
||||
"""
|
||||
Close the ClickHouse client connections.
|
||||
"""
|
||||
global clickhouse, async_clickhouse
|
||||
|
||||
try:
|
||||
if clickhouse is not None:
|
||||
clickhouse.close()
|
||||
clickhouse = None
|
||||
except Exception as e:
|
||||
# Log the error but don't raise - we still want to try closing the async client
|
||||
import logging
|
||||
|
||||
logging.getLogger(__name__).error(f"Error closing ClickHouse sync client: {e}")
|
||||
|
||||
try:
|
||||
if async_clickhouse is not None:
|
||||
await async_clickhouse.close()
|
||||
async_clickhouse = None
|
||||
except Exception as e:
|
||||
import logging
|
||||
|
||||
logging.getLogger(__name__).error(f"Error closing ClickHouse async client: {e}")
|
||||
@@ -0,0 +1,77 @@
|
||||
import asyncio
|
||||
import threading
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends
|
||||
from supabase.client import AsyncClient as AsyncSupabase
|
||||
from supabase.client import Client as Supabase
|
||||
|
||||
# Global variables to store client instances
|
||||
supabase = None
|
||||
async_supabase = None
|
||||
|
||||
# Create locks for thread-safe initialization
|
||||
_supabase_lock = threading.Lock()
|
||||
_async_supabase_lock = asyncio.Lock()
|
||||
|
||||
|
||||
def get_supabase():
|
||||
"""
|
||||
FastAPI dependency to get the synchronous Supabase client.
|
||||
This allows for proper dependency injection and easier testing.
|
||||
|
||||
Returns:
|
||||
Supabase: The synchronous Supabase client instance
|
||||
"""
|
||||
|
||||
from agentops.api.environment import SUPABASE_KEY, SUPABASE_URL
|
||||
|
||||
global supabase
|
||||
if supabase is None:
|
||||
with _supabase_lock:
|
||||
# Check again inside the lock to prevent race conditions
|
||||
if supabase is None:
|
||||
supabase = Supabase(SUPABASE_URL, SUPABASE_KEY)
|
||||
return supabase
|
||||
|
||||
|
||||
async def get_async_supabase():
|
||||
"""
|
||||
FastAPI dependency to get the async Supabase client.
|
||||
This allows for proper dependency injection and easier testing.
|
||||
|
||||
Returns:
|
||||
AsyncSupabase: The async Supabase client instance
|
||||
"""
|
||||
|
||||
from agentops.api.environment import SUPABASE_KEY, SUPABASE_URL
|
||||
|
||||
global async_supabase
|
||||
if async_supabase is None:
|
||||
async with _async_supabase_lock:
|
||||
# Check again inside the lock to prevent race conditions
|
||||
if async_supabase is None:
|
||||
async_supabase = AsyncSupabase(SUPABASE_URL, SUPABASE_KEY)
|
||||
return async_supabase
|
||||
|
||||
|
||||
# Annotated dependencies for better type hinting
|
||||
AsyncSupabaseClient = Annotated[AsyncSupabase, Depends(get_async_supabase)]
|
||||
SupabaseClient = Annotated[Supabase, Depends(get_supabase)]
|
||||
|
||||
|
||||
async def close_supabase_clients():
|
||||
"""
|
||||
Close the Supabase client connections.
|
||||
"""
|
||||
global supabase, async_supabase
|
||||
|
||||
if supabase is not None:
|
||||
# Supabase client doesn't have an explicit close method
|
||||
# but we can set it to None to allow garbage collection
|
||||
supabase = None
|
||||
|
||||
if async_supabase is not None:
|
||||
# Async Supabase client doesn't have an explicit close method
|
||||
# but we can set it to None to allow garbage collection
|
||||
async_supabase = None
|
||||
@@ -0,0 +1,27 @@
|
||||
import base64
|
||||
import pickle
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
class SpanAttributeEncoder:
|
||||
@staticmethod
|
||||
def encode(attributes: Dict[str, Any]) -> bytes:
|
||||
"""Encode span attributes to binary format."""
|
||||
return pickle.dumps(attributes)
|
||||
|
||||
@staticmethod
|
||||
def decode(binary_data: bytes) -> Dict[str, Any]:
|
||||
"""Decode binary data to span attributes."""
|
||||
return pickle.loads(binary_data)
|
||||
|
||||
@staticmethod
|
||||
def encode_to_base64(attributes: Dict[str, Any]) -> str:
|
||||
"""Encode span attributes to base64 string for debugging."""
|
||||
binary_data = SpanAttributeEncoder.encode(attributes)
|
||||
return base64.b64encode(binary_data).decode("utf-8")
|
||||
|
||||
@staticmethod
|
||||
def decode_from_base64(base64_str: str) -> Dict[str, Any]:
|
||||
"""Decode base64 string to span attributes for debugging."""
|
||||
binary_data = base64.b64decode(base64_str)
|
||||
return SpanAttributeEncoder.decode(binary_data)
|
||||
@@ -0,0 +1,76 @@
|
||||
import os
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SUPABASE_URL: str = os.getenv("SUPABASE_URL")
|
||||
SUPABASE_KEY: str = os.getenv("SUPABASE_KEY")
|
||||
|
||||
SUPABASE_S3_BUCKET: str = os.getenv("SUPABASE_S3_BUCKET")
|
||||
SUPABASE_S3_LOGS_BUCKET: str = os.getenv("SUPABASE_S3_LOGS_BUCKET")
|
||||
SUPABASE_S3_ACCESS_KEY_ID: str = os.getenv("SUPABASE_S3_ACCESS_KEY_ID")
|
||||
SUPABASE_S3_SECRET_ACCESS_KEY: str = os.getenv("SUPABASE_S3_SECRET_ACCESS_KEY")
|
||||
|
||||
JWT_SECRET_KEY: str = os.getenv("JWT_SECRET_KEY")
|
||||
|
||||
CLICKHOUSE_HOST: str = os.getenv("CLICKHOUSE_HOST")
|
||||
CLICKHOUSE_PORT: int = int(os.getenv("CLICKHOUSE_PORT", 0))
|
||||
CLICKHOUSE_USER: str = os.getenv("CLICKHOUSE_USER", "")
|
||||
CLICKHOUSE_PASSWORD: str = os.getenv("CLICKHOUSE_PASSWORD", "")
|
||||
CLICKHOUSE_DATABASE: str = os.getenv("CLICKHOUSE_DATABASE", "")
|
||||
CLICKHOUSE_SECURE: bool = os.getenv("CLICKHOUSE_SECURE", "false").lower() in ("1", "true", "yes")
|
||||
|
||||
|
||||
PROFILING_ENABLED: bool = os.environ.get("PROFILING_ENABLED", "false").lower() == "true"
|
||||
PROFILING_FORMAT: str = os.environ.get("PROFILING_FORMAT", "html")
|
||||
if PROFILING_FORMAT not in ["html", "speedscope"]:
|
||||
PROFILING_FORMAT = "html"
|
||||
PROFILING_OUTPUT_DIR: str = os.environ.get("PROFILING_OUTPUT_DIR", ".")
|
||||
|
||||
# Stripe Configuration
|
||||
STRIPE_WEBHOOK_SECRET: str = os.getenv("STRIPE_WEBHOOK_SECRET", "")
|
||||
STRIPE_SECRET_KEY: str = os.getenv("STRIPE_SECRET_KEY", "")
|
||||
STRIPE_SUBSCRIPTION_PRICE_ID: str = os.getenv("STRIPE_SUBSCRIPTION_PRICE_ID", "")
|
||||
STRIPE_TOKEN_PRICE_ID: str = os.getenv("STRIPE_TOKEN_PRICE_ID", "")
|
||||
STRIPE_SPAN_PRICE_ID: str = os.getenv("STRIPE_SPAN_PRICE_ID", "")
|
||||
|
||||
|
||||
# Log Stripe configuration status on module load
|
||||
def _log_stripe_config():
|
||||
"""Log the status of Stripe environment variables for debugging"""
|
||||
stripe_vars = {
|
||||
"STRIPE_SECRET_KEY": STRIPE_SECRET_KEY,
|
||||
"STRIPE_WEBHOOK_SECRET": STRIPE_WEBHOOK_SECRET,
|
||||
"STRIPE_SUBSCRIPTION_PRICE_ID": STRIPE_SUBSCRIPTION_PRICE_ID,
|
||||
"STRIPE_TOKEN_PRICE_ID": STRIPE_TOKEN_PRICE_ID,
|
||||
"STRIPE_SPAN_PRICE_ID": STRIPE_SPAN_PRICE_ID,
|
||||
}
|
||||
|
||||
logger.info("=== Stripe Configuration Status ===")
|
||||
found_count = 0
|
||||
missing_vars = []
|
||||
for var_name, var_value in stripe_vars.items():
|
||||
if var_value:
|
||||
# Show first 8 characters for verification without exposing secrets
|
||||
masked_value = f"{var_value[:8]}..." if len(var_value) > 8 else var_value
|
||||
logger.info(f"✓ {var_name}: {masked_value}")
|
||||
found_count += 1
|
||||
else:
|
||||
logger.warning(f"✗ {var_name}: NOT FOUND")
|
||||
missing_vars.append(var_name)
|
||||
|
||||
logger.info(f"Stripe configuration: {found_count}/{len(stripe_vars)} variables found")
|
||||
|
||||
if missing_vars:
|
||||
logger.error(f"MISSING STRIPE VARIABLES: {', '.join(missing_vars)}")
|
||||
logger.error("These variables are required for proper Stripe integration:")
|
||||
for var in missing_vars:
|
||||
logger.error(f" - {var}")
|
||||
else:
|
||||
logger.info("✓ All Stripe environment variables are configured")
|
||||
|
||||
logger.info("==================================")
|
||||
|
||||
|
||||
# Call the logging function when module is imported
|
||||
_log_stripe_config()
|
||||
@@ -0,0 +1,206 @@
|
||||
import base64
|
||||
import uuid
|
||||
import datetime
|
||||
import json
|
||||
from decimal import Decimal
|
||||
from tokencost import TOKEN_COSTS, count_string_tokens, count_message_tokens
|
||||
from jsonschema import validate
|
||||
from jsonschema.exceptions import ValidationError
|
||||
|
||||
from agentops.api.promptarmor import get_promptarmor_flag
|
||||
from agentops.api.log_config import logger
|
||||
from agentops.api.exceptions import InvalidModelError
|
||||
from agentops.api.db.supabase_client import AsyncSupabaseClient, get_async_supabase
|
||||
from agentops.api.environment import SUPABASE_URL
|
||||
|
||||
|
||||
async def handle_actions(event, session_id, supabase: AsyncSupabaseClient = None):
|
||||
if supabase is None:
|
||||
supabase = await get_async_supabase()
|
||||
|
||||
async def process_screenshot(screenshot, session_id):
|
||||
if screenshot is None:
|
||||
return None
|
||||
|
||||
if screenshot.startswith("http://") or screenshot.startswith("https://"):
|
||||
return screenshot
|
||||
|
||||
# screenshot is a base64 string
|
||||
base64_img_bytes = screenshot.replace("data:image/png;base64,", "")
|
||||
base64_img_bytes += "=" * ((4 - len(base64_img_bytes) % 4) % 4)
|
||||
img_bytes = base64.b64decode(base64_img_bytes)
|
||||
timestamp_utc = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
|
||||
try:
|
||||
await supabase.storage.from_("screenshots").upload(f"{session_id}/{timestamp_utc}.png", img_bytes)
|
||||
except RuntimeError as e:
|
||||
logger.warning(f"Error posting screenshot: {e}")
|
||||
return None
|
||||
|
||||
return f"{SUPABASE_URL}/storage/v1/object/screenshots/{session_id}/{timestamp_utc}.png"
|
||||
|
||||
action = {
|
||||
"id": event.get("id", str(uuid.uuid4())),
|
||||
"session_id": session_id,
|
||||
"agent_id": event.get("agent_id", None),
|
||||
"action_type": event.get("action_type", None),
|
||||
"logs": event.get("logs", None),
|
||||
"screenshot": await process_screenshot(event.get("screenshot", None), session_id),
|
||||
"params": event.get("params", None),
|
||||
"returns": event.get("returns", None),
|
||||
"init_timestamp": event["init_timestamp"],
|
||||
"end_timestamp": event["end_timestamp"],
|
||||
}
|
||||
return action
|
||||
|
||||
|
||||
async def handle_llms(event, premium, session_id, supabase: AsyncSupabaseClient = None):
|
||||
if supabase is None:
|
||||
supabase = await get_async_supabase()
|
||||
|
||||
def count_prompt_tokens(prompt):
|
||||
try:
|
||||
if model not in TOKEN_COSTS:
|
||||
raise InvalidModelError(f'Invalid model "{model}" provided.')
|
||||
if type(prompt) is str:
|
||||
return count_string_tokens(prompt, model)
|
||||
else:
|
||||
return count_message_tokens(prompt, model)
|
||||
except Exception as e:
|
||||
logger.warning(e)
|
||||
return 0
|
||||
|
||||
def count_completion_tokens(completion):
|
||||
try:
|
||||
if model not in TOKEN_COSTS:
|
||||
raise InvalidModelError(f'Invalid model "{model}" provided.')
|
||||
# User may send dict containing the completion content or just the completion content
|
||||
# completion = {role:"assistant", content:"some message", function_call: ..., tool_calls: ...}
|
||||
# completion = "some message"
|
||||
return count_string_tokens(completion.get("content", completion), model)
|
||||
except Exception as e:
|
||||
logger.warning(e)
|
||||
return 0
|
||||
|
||||
chatml_schema_prompt = {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["role"],
|
||||
"properties": {
|
||||
"role": {"type": "string"},
|
||||
"name": {"type": "string"},
|
||||
"content": {
|
||||
"oneOf": [
|
||||
{"type": ["string", "null"]},
|
||||
{"type": "array"},
|
||||
{"type": "object"},
|
||||
]
|
||||
},
|
||||
"tool_calls": {"type": ["array", "null"]},
|
||||
"tool_call_id": {"type": ["string", "null"]},
|
||||
},
|
||||
"additionalProperties": True,
|
||||
},
|
||||
}
|
||||
|
||||
chatml_schema_completion = {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"type": "object",
|
||||
"required": ["role"],
|
||||
"properties": {
|
||||
"role": {"type": "string"},
|
||||
"content": {"type": ["string", "null", "object", "array"]},
|
||||
"tool_calls": {"type": ["array", "null"]},
|
||||
"function_call": {"type": ["object", "null"]},
|
||||
},
|
||||
"additionalProperties": True,
|
||||
}
|
||||
|
||||
def coerce_llm_message_to_chatml_schema(message, chatml_schema):
|
||||
try:
|
||||
validate(instance=message, schema=chatml_schema)
|
||||
|
||||
wrapped_message = {"type": "chatml", "messages": message}
|
||||
return wrapped_message
|
||||
except ValidationError:
|
||||
# If validation fails, wrap the message as a "string" type
|
||||
wrapped_message = {
|
||||
"type": "string",
|
||||
"string": (json.dumps(message) if not isinstance(message, str) else message),
|
||||
}
|
||||
|
||||
return wrapped_message
|
||||
|
||||
model = event.get("model", None)
|
||||
prompt = event.get("prompt", None)
|
||||
completion = event.get("completion", None)
|
||||
prompt_tokens = event.get("prompt_tokens") or count_prompt_tokens(prompt)
|
||||
completion_tokens = event.get("completion_tokens") or count_completion_tokens(completion)
|
||||
|
||||
if premium:
|
||||
promptarmor_flag = await get_promptarmor_flag(prompt, completion, session_id)
|
||||
else:
|
||||
promptarmor_flag = None
|
||||
|
||||
cost = event.get("cost")
|
||||
if (cost is None) and (model in TOKEN_COSTS):
|
||||
cost_per_prompt_token = Decimal(str(TOKEN_COSTS[model]["input_cost_per_token"]))
|
||||
cost_per_completion_token = Decimal(str(TOKEN_COSTS[model]["output_cost_per_token"]))
|
||||
cost = str((prompt_tokens * cost_per_prompt_token) + (completion_tokens * cost_per_completion_token))
|
||||
|
||||
llm = {
|
||||
"id": event.get("id", str(uuid.uuid4())),
|
||||
"session_id": session_id,
|
||||
"agent_id": event.get("agent_id", None),
|
||||
"thread_id": event.get("thread_id", None),
|
||||
"prompt": coerce_llm_message_to_chatml_schema(prompt, chatml_schema_prompt),
|
||||
"completion": coerce_llm_message_to_chatml_schema(completion, chatml_schema_completion),
|
||||
"model": model,
|
||||
"prompt_tokens": prompt_tokens,
|
||||
"completion_tokens": completion_tokens,
|
||||
"cost": cost,
|
||||
"promptarmor_flag": promptarmor_flag,
|
||||
"params": event.get("params", None),
|
||||
"returns": event.get("returns", None),
|
||||
"init_timestamp": event["init_timestamp"],
|
||||
"end_timestamp": event["end_timestamp"],
|
||||
}
|
||||
|
||||
return llm
|
||||
|
||||
|
||||
async def handle_tools(event, session_id, supabase: AsyncSupabaseClient = None):
|
||||
if supabase is None:
|
||||
supabase = await get_async_supabase()
|
||||
|
||||
tool = {
|
||||
"id": event.get("id", str(uuid.uuid4())),
|
||||
"session_id": session_id,
|
||||
"agent_id": event.get("agent_id", None),
|
||||
"name": event.get("name", None),
|
||||
"logs": event.get("logs", None),
|
||||
"params": event.get("params", None),
|
||||
"returns": event.get("returns", None),
|
||||
"init_timestamp": event["init_timestamp"],
|
||||
"end_timestamp": event["end_timestamp"],
|
||||
}
|
||||
return tool
|
||||
|
||||
|
||||
async def handle_errors(event, session_id, supabase: AsyncSupabaseClient = None):
|
||||
if supabase is None:
|
||||
supabase = await get_async_supabase()
|
||||
|
||||
error = {
|
||||
"session_id": session_id,
|
||||
"trigger_event_id": event.get("trigger_event_id", None),
|
||||
"trigger_event_type": event.get("trigger_event_type", None),
|
||||
"error_type": event.get("error_type", None),
|
||||
"code": event.get("code", None),
|
||||
"details": event.get("details", None),
|
||||
"logs": event.get("logs", None),
|
||||
"timestamp": event.get("timestamp", None),
|
||||
}
|
||||
return error
|
||||
@@ -0,0 +1,18 @@
|
||||
class InvalidAPIKeyError(RuntimeError):
|
||||
def __init__(self, code, message):
|
||||
self.message = message
|
||||
self.code = code
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class ExpiredJWTError(RuntimeError):
|
||||
def __init__(self, code, message):
|
||||
self.message = message
|
||||
self.code = code
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class InvalidModelError(Exception):
|
||||
def __init__(self, msg):
|
||||
super().__init__(msg)
|
||||
pass
|
||||
@@ -0,0 +1,8 @@
|
||||
Interactors implement business logic that are used to interact with the database.
|
||||
|
||||
They are responsible for:
|
||||
|
||||
- Formatting data for the database
|
||||
- Validating data for the database
|
||||
- Performing database operations
|
||||
- Returning the results
|
||||
@@ -0,0 +1,177 @@
|
||||
from enum import Enum
|
||||
from typing import Any, Dict
|
||||
|
||||
from opentelemetry.semconv._incubating.attributes.gen_ai_attributes import (
|
||||
GEN_AI_OPERATION_NAME,
|
||||
GEN_AI_REQUEST_MODEL,
|
||||
GEN_AI_RESPONSE_MODEL,
|
||||
GEN_AI_SYSTEM,
|
||||
GenAiOperationNameValues,
|
||||
)
|
||||
from opentelemetry.semconv_ai import LLMRequestTypeValues, SpanAttributes
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
from agentops.api.encoders.spans import SpanAttributeEncoder
|
||||
|
||||
|
||||
# ==========================================
|
||||
# Internal Span Classifications
|
||||
# ==========================================
|
||||
class AgentopsSpanType(str, Enum):
|
||||
"""Internal classification of span types for AgentOps processing."""
|
||||
|
||||
SESSION_UPDATE = "session_update"
|
||||
GEN_AI = "gen_ai"
|
||||
LOG = "log"
|
||||
|
||||
|
||||
class AgentopsGenAISpanSubtype(str, Enum):
|
||||
"""Internal classification of GenAI span subtypes for AgentOps processing.
|
||||
|
||||
Note: These are NOT OpenTelemetry standard span types, but rather
|
||||
internal classifications used by AgentOps for processing."""
|
||||
|
||||
CHAT = "gen_ai_chat"
|
||||
COMPLETION = "gen_ai_completion"
|
||||
TOOL = "gen_ai_tool"
|
||||
EMBEDDING = "gen_ai_embedding"
|
||||
GENERIC = "gen_ai" # Generic/fallback type
|
||||
|
||||
|
||||
# Legacy/alternative attributes (used in some implementations)
|
||||
LEGACY_SYSTEM = "ai.system"
|
||||
LEGACY_LLM = "ai.llm"
|
||||
LEGACY_EMBEDDING = "ai.embedding"
|
||||
|
||||
# Tool attributes - these aren't yet in the standard, so we define them here
|
||||
GEN_AI_TOOL_NAME = "gen_ai.tool.name"
|
||||
GEN_AI_TOOL_CALL_ID = "gen_ai.tool.call.id"
|
||||
|
||||
# Log attributes
|
||||
LOG_SEVERITY = "log.severity"
|
||||
LOG_MESSAGE = "log.message"
|
||||
|
||||
|
||||
async def classify_span(span: Dict[str, Any]) -> str:
|
||||
"""Classify a span based on semantic conventions."""
|
||||
# Get span attributes
|
||||
attributes = span.get("attributes", {})
|
||||
|
||||
# Check for Gen AI spans using multiple criteria
|
||||
if (
|
||||
LEGACY_SYSTEM in attributes
|
||||
or LEGACY_LLM in attributes
|
||||
or LEGACY_EMBEDDING in attributes
|
||||
or GEN_AI_SYSTEM in attributes
|
||||
or GEN_AI_OPERATION_NAME in attributes
|
||||
or GEN_AI_REQUEST_MODEL in attributes
|
||||
or GEN_AI_RESPONSE_MODEL in attributes
|
||||
or SpanAttributes.LLM_REQUEST_MODEL in attributes
|
||||
or SpanAttributes.LLM_RESPONSE_MODEL in attributes
|
||||
or SpanAttributes.LLM_SYSTEM in attributes
|
||||
):
|
||||
return AgentopsSpanType.GEN_AI
|
||||
|
||||
# Check for Log spans
|
||||
if LOG_SEVERITY in attributes or LOG_MESSAGE in attributes:
|
||||
return AgentopsSpanType.LOG
|
||||
|
||||
# Default to Session Update span
|
||||
return AgentopsSpanType.SESSION_UPDATE
|
||||
|
||||
|
||||
async def classify_gen_ai_span_subtype(span: Dict[str, Any]) -> str:
|
||||
"""Further classify a Gen AI span into subtypes based on attributes."""
|
||||
attributes = span.get("attributes", {})
|
||||
|
||||
# Check for tool usage
|
||||
if GEN_AI_TOOL_NAME in attributes or GEN_AI_TOOL_CALL_ID in attributes:
|
||||
return AgentopsGenAISpanSubtype.TOOL
|
||||
|
||||
# Check for operation type
|
||||
operation_name = attributes.get(GEN_AI_OPERATION_NAME)
|
||||
if operation_name:
|
||||
if operation_name == GenAiOperationNameValues.CHAT.value:
|
||||
return AgentopsGenAISpanSubtype.CHAT
|
||||
elif operation_name == GenAiOperationNameValues.TEXT_COMPLETION.value:
|
||||
return AgentopsGenAISpanSubtype.COMPLETION
|
||||
elif operation_name == GenAiOperationNameValues.EMBEDDINGS.value:
|
||||
return AgentopsGenAISpanSubtype.EMBEDDING
|
||||
|
||||
# Check for request type from LLMRequestTypeValues
|
||||
request_type = attributes.get(SpanAttributes.LLM_REQUEST_TYPE)
|
||||
if request_type:
|
||||
if request_type == LLMRequestTypeValues.CHAT.value:
|
||||
return AgentopsGenAISpanSubtype.CHAT
|
||||
elif request_type == LLMRequestTypeValues.COMPLETION.value:
|
||||
return AgentopsGenAISpanSubtype.COMPLETION
|
||||
elif request_type == LLMRequestTypeValues.EMBEDDING.value:
|
||||
return AgentopsGenAISpanSubtype.EMBEDDING
|
||||
|
||||
# Check for embedding-specific attributes
|
||||
if LEGACY_EMBEDDING in attributes:
|
||||
return AgentopsGenAISpanSubtype.EMBEDDING
|
||||
|
||||
# Default to general Gen AI span
|
||||
return AgentopsGenAISpanSubtype.GENERIC
|
||||
|
||||
|
||||
async def handle_session_update_span(span: Dict[str, Any], session_id: str) -> Dict[str, Any]:
|
||||
"""Handle a session update span."""
|
||||
# Extract span data
|
||||
span_data = {
|
||||
"session_id": session_id,
|
||||
"agent_id": span.get("agent_id"),
|
||||
"trace_id": span.get("trace_id"),
|
||||
"span_id": span.get("span_id"),
|
||||
"parent_span_id": span.get("parent_span_id"),
|
||||
"name": span.get("name"),
|
||||
"kind": span.get("kind", SpanKind.INTERNAL),
|
||||
"start_time": span.get("start_time"),
|
||||
"end_time": span.get("end_time"),
|
||||
"attributes": SpanAttributeEncoder.encode(span.get("attributes", {})),
|
||||
"span_type": AgentopsSpanType.SESSION_UPDATE,
|
||||
}
|
||||
return span_data
|
||||
|
||||
|
||||
async def handle_gen_ai_span(span: Dict[str, Any], session_id: str) -> Dict[str, Any]:
|
||||
"""Handle a Gen AI span."""
|
||||
# Get the Gen AI span subtype
|
||||
gen_ai_subtype = await classify_gen_ai_span_subtype(span)
|
||||
|
||||
# Extract span data
|
||||
span_data = {
|
||||
"session_id": session_id,
|
||||
"agent_id": span.get("agent_id"),
|
||||
"trace_id": span.get("trace_id"),
|
||||
"span_id": span.get("span_id"),
|
||||
"parent_span_id": span.get("parent_span_id"),
|
||||
"name": span.get("name"),
|
||||
"kind": span.get("kind", SpanKind.CLIENT),
|
||||
"start_time": span.get("start_time"),
|
||||
"end_time": span.get("end_time"),
|
||||
"attributes": SpanAttributeEncoder.encode(span.get("attributes", {})),
|
||||
"span_type": AgentopsSpanType.GEN_AI,
|
||||
"span_subtype": gen_ai_subtype,
|
||||
}
|
||||
return span_data
|
||||
|
||||
|
||||
async def handle_log_span(span: Dict[str, Any], session_id: str) -> Dict[str, Any]:
|
||||
"""Handle a log span."""
|
||||
# Extract span data
|
||||
span_data = {
|
||||
"session_id": session_id,
|
||||
"agent_id": span.get("agent_id"),
|
||||
"trace_id": span.get("trace_id"),
|
||||
"span_id": span.get("span_id"),
|
||||
"parent_span_id": span.get("parent_span_id"),
|
||||
"name": span.get("name"),
|
||||
"kind": span.get("kind", SpanKind.INTERNAL),
|
||||
"start_time": span.get("start_time"),
|
||||
"end_time": span.get("end_time"),
|
||||
"attributes": SpanAttributeEncoder.encode(span.get("attributes", {})),
|
||||
"span_type": AgentopsSpanType.LOG,
|
||||
}
|
||||
return span_data
|
||||
@@ -0,0 +1,43 @@
|
||||
import logging
|
||||
import os
|
||||
|
||||
# Simple logging configuration
|
||||
log_levels = {
|
||||
"CRITICAL": logging.CRITICAL,
|
||||
"ERROR": logging.ERROR,
|
||||
"WARNING": logging.WARNING,
|
||||
"INFO": logging.INFO,
|
||||
"DEBUG": logging.DEBUG,
|
||||
}
|
||||
|
||||
|
||||
def setup_logger(name: str = "AgentOpsAPI") -> logging.Logger:
|
||||
"""Set up and configure a logger with the specified name."""
|
||||
logging_level: str = os.environ.get("LOGGING_LEVEL", "INFO")
|
||||
level = log_levels.get(logging_level.upper(), logging.INFO)
|
||||
|
||||
# Create logger
|
||||
logger = logging.getLogger(name)
|
||||
logger.setLevel(level)
|
||||
logger.propagate = False
|
||||
|
||||
# Clear existing handlers to avoid duplicates when reloading in dev
|
||||
if logger.handlers:
|
||||
logger.handlers.clear()
|
||||
|
||||
# Create console handler
|
||||
handler = logging.StreamHandler()
|
||||
handler.setLevel(level)
|
||||
|
||||
# Create formatter
|
||||
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
|
||||
handler.setFormatter(formatter)
|
||||
|
||||
# Add handler to logger
|
||||
logger.addHandler(handler)
|
||||
|
||||
return logger
|
||||
|
||||
|
||||
# Create the main application logger
|
||||
logger = setup_logger()
|
||||
@@ -0,0 +1,439 @@
|
||||
from typing import Any, Optional
|
||||
from functools import cached_property
|
||||
from decimal import Decimal
|
||||
from datetime import datetime, date
|
||||
import pydantic
|
||||
|
||||
from agentops.api.db.clickhouse.models import ClickhouseAggregatedModel, SelectFields, FilterFields
|
||||
from agentops.api.models.traces import BaseTraceModel
|
||||
|
||||
from .span_metrics import SpanMetricsMixin, TraceMetricsMixin
|
||||
|
||||
|
||||
class TraceCountsModel(BaseTraceModel):
|
||||
"""
|
||||
Model representing the metrics for all of a user's projects.
|
||||
This model is used to generate aggregated metrics for projects.
|
||||
"""
|
||||
|
||||
project_id: str
|
||||
span_count: int
|
||||
trace_count: int
|
||||
|
||||
@pydantic.model_validator(mode='before')
|
||||
@classmethod
|
||||
def fix_project_id(cls, values: dict[str, Any]) -> dict[str, Any]:
|
||||
"""project_id_ comes from the query, but we want to use project_id."""
|
||||
values['project_id'] = values.get('project_id_')
|
||||
return values
|
||||
|
||||
@classmethod
|
||||
def _get_select_query(
|
||||
cls,
|
||||
*,
|
||||
fields: Optional[SelectFields] = None,
|
||||
filters: Optional[FilterFields] = None,
|
||||
search: Optional[str] = None,
|
||||
order_by: Optional[str] = None,
|
||||
offset: Optional[int] = None,
|
||||
limit: Optional[int] = None,
|
||||
) -> tuple[str, dict[str, Any]]:
|
||||
if fields or order_by or offset or limit or search:
|
||||
raise NotImplementedError("Custom fields, search, order_by, offset or limit are not supported.")
|
||||
|
||||
where_clause, params = cls._get_where_clause(**(filters or {}))
|
||||
query = f"""
|
||||
SELECT
|
||||
any(project_id) as project_id_, -- cannot reassign project_id
|
||||
count() as span_count,
|
||||
count(DISTINCT TraceId) as trace_count
|
||||
FROM {cls.table_name}
|
||||
{f"WHERE {where_clause}" if where_clause else ""}
|
||||
GROUP BY project_id
|
||||
"""
|
||||
return query, params
|
||||
|
||||
|
||||
class ProjectMetricsTraceModel(SpanMetricsMixin, BaseTraceModel):
|
||||
"""
|
||||
Model representing a single span in the project metrics.
|
||||
|
||||
This model extends the base TraceModel to include additional properties and methods
|
||||
for calculating token costs and other trace-related metrics.
|
||||
|
||||
Incorporates SpanMetricsMixin to handle token calculations.
|
||||
"""
|
||||
|
||||
selectable_fields = {
|
||||
"TraceId": "trace_id",
|
||||
"Timestamp": "timestamp",
|
||||
"StatusCode": "status_code",
|
||||
}
|
||||
|
||||
trace_id: str
|
||||
timestamp: datetime
|
||||
status_code: str
|
||||
|
||||
# Add span count fields for aggregated metrics
|
||||
span_count: int = 1 # Number of spans in this trace
|
||||
success_span_count: int = 0
|
||||
fail_span_count: int = 0
|
||||
indeterminate_span_count: int = 0
|
||||
|
||||
# Track if we have costs (either stored or calculable via model info)
|
||||
has_cached_costs: int = 0
|
||||
|
||||
@pydantic.field_validator(
|
||||
'span_count',
|
||||
'success_span_count',
|
||||
'fail_span_count',
|
||||
'indeterminate_span_count',
|
||||
'has_cached_costs',
|
||||
mode='before',
|
||||
)
|
||||
@classmethod
|
||||
def ensure_span_counts_int(cls, v: Any) -> int:
|
||||
"""Ensure that all counts are always an integer."""
|
||||
return int(v or 0)
|
||||
|
||||
@classmethod
|
||||
def _get_select_query(
|
||||
cls,
|
||||
*,
|
||||
fields: Optional[SelectFields] = None,
|
||||
filters: Optional[FilterFields] = None,
|
||||
search: Optional[str] = None,
|
||||
order_by: Optional[str] = None,
|
||||
offset: Optional[int] = None,
|
||||
limit: Optional[int] = None,
|
||||
) -> tuple[str, dict[str, Any]]:
|
||||
"""
|
||||
Override to aggregate metrics at the database level instead of fetching all rows.
|
||||
This dramatically reduces data transfer and processing time.
|
||||
|
||||
For costs: Uses stored costs when available, calculates on-the-fly for missing data.
|
||||
This preserves 100% accurate costs for new data while fixing historical gaps.
|
||||
"""
|
||||
where_clause, params = cls._get_where_clause(**(filters or {}))
|
||||
|
||||
# Instead of selecting individual rows, aggregate by trace
|
||||
# This processes ALL spans matching the filters but returns one row per trace
|
||||
query = f"""
|
||||
SELECT
|
||||
TraceId as trace_id,
|
||||
max(Timestamp) as timestamp,
|
||||
argMax(StatusCode, Timestamp) as status_code,
|
||||
count() as span_count,
|
||||
countIf(upper(StatusCode) = 'OK') as success_span_count,
|
||||
countIf(upper(StatusCode) = 'ERROR') as fail_span_count,
|
||||
countIf(upper(StatusCode) NOT IN ('OK', 'ERROR')) as indeterminate_span_count,
|
||||
sum(toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.prompt_tokens'], '0'))) as prompt_tokens,
|
||||
sum(toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.completion_tokens'], '0'))) as completion_tokens,
|
||||
sum(toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.cache_read_input_tokens'], '0'))) as cache_read_input_tokens,
|
||||
sum(toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.reasoning_tokens'], '0'))) as reasoning_tokens,
|
||||
sum(
|
||||
if(
|
||||
SpanAttributes['gen_ai.usage.total_tokens'] != '',
|
||||
toUInt64OrZero(SpanAttributes['gen_ai.usage.total_tokens']),
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.prompt_tokens'], '0')) +
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.completion_tokens'], '0')) +
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.cache_read_input_tokens'], '0')) +
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.reasoning_tokens'], '0'))
|
||||
)
|
||||
) as cached_total_tokens,
|
||||
any(SpanAttributes['gen_ai.request.model']) as request_model,
|
||||
any(SpanAttributes['gen_ai.response.model']) as response_model,
|
||||
sum(
|
||||
if(
|
||||
SpanAttributes['gen_ai.usage.prompt_cost'] != '',
|
||||
toDecimal64OrZero(SpanAttributes['gen_ai.usage.prompt_cost'], 9),
|
||||
toDecimal64(
|
||||
calculate_prompt_cost(
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.prompt_tokens'], '0')),
|
||||
coalesce(
|
||||
nullIf(SpanAttributes['gen_ai.response.model'], ''),
|
||||
nullIf(SpanAttributes['gen_ai.request.model'], '')
|
||||
)
|
||||
),
|
||||
9
|
||||
)
|
||||
)
|
||||
) as cached_prompt_cost,
|
||||
sum(
|
||||
if(
|
||||
SpanAttributes['gen_ai.usage.completion_cost'] != '',
|
||||
toDecimal64OrZero(SpanAttributes['gen_ai.usage.completion_cost'], 9),
|
||||
toDecimal64(
|
||||
calculate_completion_cost(
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.completion_tokens'], '0')),
|
||||
coalesce(
|
||||
nullIf(SpanAttributes['gen_ai.response.model'], ''),
|
||||
nullIf(SpanAttributes['gen_ai.request.model'], '')
|
||||
)
|
||||
),
|
||||
9
|
||||
)
|
||||
)
|
||||
) as cached_completion_cost,
|
||||
cached_prompt_cost + cached_completion_cost as cached_total_cost,
|
||||
countIf(
|
||||
SpanAttributes['gen_ai.usage.prompt_cost'] != ''
|
||||
OR SpanAttributes['gen_ai.usage.completion_cost'] != ''
|
||||
OR coalesce(
|
||||
nullIf(SpanAttributes['gen_ai.response.model'], ''),
|
||||
nullIf(SpanAttributes['gen_ai.request.model'], '')
|
||||
) != ''
|
||||
) as has_cached_costs
|
||||
FROM {cls.table_name}
|
||||
{f"WHERE {where_clause}" if where_clause else ""}
|
||||
GROUP BY TraceId
|
||||
ORDER BY timestamp DESC
|
||||
"""
|
||||
|
||||
return query, params
|
||||
|
||||
|
||||
class ProjectMetricsDurationModel(BaseTraceModel):
|
||||
"""
|
||||
Model representing the duration metrics for a project.
|
||||
|
||||
This model is used to generate aggregated duration metrics for traces in a project.
|
||||
"""
|
||||
|
||||
min_duration: int
|
||||
max_duration: int
|
||||
avg_duration: int
|
||||
total_duration: int
|
||||
span_count: int
|
||||
trace_count: int
|
||||
start_time: datetime
|
||||
end_time: datetime
|
||||
|
||||
@pydantic.field_validator(
|
||||
'min_duration',
|
||||
'max_duration',
|
||||
'avg_duration',
|
||||
'total_duration',
|
||||
'span_count',
|
||||
'trace_count',
|
||||
mode='before',
|
||||
)
|
||||
@classmethod
|
||||
def ensure_int(cls, v: Any) -> int:
|
||||
"""Ensure that all token counts are always an integer."""
|
||||
return int(v or 0)
|
||||
|
||||
@classmethod
|
||||
def _get_select_query(
|
||||
cls,
|
||||
*,
|
||||
fields: Optional[SelectFields] = None,
|
||||
filters: Optional[FilterFields] = None,
|
||||
search: Optional[str] = None,
|
||||
order_by: Optional[str] = None,
|
||||
offset: Optional[int] = None,
|
||||
limit: Optional[int] = None,
|
||||
) -> tuple[str, dict[str, Any]]:
|
||||
if fields or search or order_by or offset or limit:
|
||||
raise NotImplementedError("Custom fields, search, order_by, offset or limit are not supported.")
|
||||
|
||||
where_clause, params = cls._get_where_clause(**(filters or {}))
|
||||
query = f"""
|
||||
SELECT
|
||||
min(if(Duration > 0, Duration, null)) as min_duration,
|
||||
max(if(Duration > 0, Duration, null)) as max_duration,
|
||||
avg(if(Duration > 0, Duration, null)) as avg_duration,
|
||||
sum(if(Duration > 0, Duration, null)) as total_duration,
|
||||
count() as span_count,
|
||||
count(DISTINCT TraceId) as trace_count,
|
||||
min(Timestamp) as start_time,
|
||||
max(Timestamp) as end_time
|
||||
FROM {cls.table_name}
|
||||
{f"WHERE {where_clause}" if where_clause else ""}
|
||||
"""
|
||||
return query, params
|
||||
|
||||
|
||||
class ProjectMetricsTraceDurationsModel(BaseTraceModel):
|
||||
"""
|
||||
Model representing the trace durations for a project.
|
||||
|
||||
This is used for generating the graph that shows the duration of each trace.
|
||||
"""
|
||||
|
||||
trace_id: str
|
||||
trace_duration: int
|
||||
|
||||
@pydantic.field_validator('trace_duration', mode='before')
|
||||
@classmethod
|
||||
def ensure_int(cls, v):
|
||||
"""Ensure that trace_duration is always an integer."""
|
||||
return int(v or 0)
|
||||
|
||||
@classmethod
|
||||
def _get_select_query(
|
||||
cls,
|
||||
*,
|
||||
fields: Optional[SelectFields] = None,
|
||||
filters: Optional[FilterFields] = None,
|
||||
search: Optional[str] = None,
|
||||
order_by: Optional[str] = None,
|
||||
offset: Optional[int] = None,
|
||||
limit: Optional[int] = None,
|
||||
) -> tuple[str, dict[str, Any]]:
|
||||
if fields or search or order_by or offset or limit:
|
||||
raise NotImplementedError("Custom fields, search, order_by, offset or limit are not supported.")
|
||||
|
||||
where_clause, params = cls._get_where_clause(**(filters or {}))
|
||||
query = f"""
|
||||
SELECT
|
||||
TraceId as trace_id,
|
||||
sum(Duration) as trace_duration
|
||||
FROM {cls.table_name}
|
||||
{f"WHERE {where_clause}" if where_clause else ""}
|
||||
GROUP BY TraceId
|
||||
ORDER BY trace_duration ASC
|
||||
"""
|
||||
return query, params
|
||||
|
||||
|
||||
class ProjectMetricsModel(TraceMetricsMixin, ClickhouseAggregatedModel):
|
||||
"""
|
||||
Model representing aggregated project metrics, combining multiple Clickhouse models.
|
||||
|
||||
This model aggregates trace metrics, duration metrics, and trace durations into a single
|
||||
response. It computes various summary statistics and provides properties for easy access to
|
||||
common metrics like average tokens and cost calculations.
|
||||
"""
|
||||
|
||||
aggregated_models = (
|
||||
ProjectMetricsTraceModel,
|
||||
ProjectMetricsDurationModel,
|
||||
ProjectMetricsTraceDurationsModel,
|
||||
)
|
||||
|
||||
trace_metrics_field_name = "traces"
|
||||
|
||||
traces: list[ProjectMetricsTraceModel] = pydantic.Field(default_factory=list)
|
||||
duration: ProjectMetricsDurationModel
|
||||
trace_durations: list[ProjectMetricsTraceDurationsModel] = pydantic.Field(default_factory=list)
|
||||
|
||||
trace_cost_dates: dict[date, Decimal] = pydantic.Field(default_factory=dict)
|
||||
success_dates: list[datetime] = pydantic.Field(default_factory=list)
|
||||
fail_dates: list[datetime] = pydantic.Field(default_factory=list)
|
||||
indeterminate_dates: list[datetime] = pydantic.Field(default_factory=list)
|
||||
|
||||
# Track if we have any cost data (stored or calculable) for proper display
|
||||
has_any_cached_costs: bool = False
|
||||
|
||||
# Initialize parent class attributes
|
||||
span_count: int = 0
|
||||
trace_count: int = 0
|
||||
success_count: int = 0
|
||||
fail_count: int = 0
|
||||
indeterminate_count: int = 0
|
||||
|
||||
total_tokens: int = 0
|
||||
success_tokens: int = 0
|
||||
fail_tokens: int = 0
|
||||
|
||||
prompt_tokens: int = 0
|
||||
completion_tokens: int = 0
|
||||
cache_read_input_tokens: int = 0
|
||||
reasoning_tokens: int = 0
|
||||
|
||||
prompt_cost: Decimal = Decimal(0)
|
||||
completion_cost: Decimal = Decimal(0)
|
||||
total_cost: Decimal = Decimal(0)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
traces: list[ProjectMetricsTraceModel],
|
||||
durations: list[ProjectMetricsDurationModel],
|
||||
trace_durations: list[ProjectMetricsTraceDurationsModel],
|
||||
) -> None:
|
||||
super().__init__(traces=traces, duration=durations[0], trace_durations=trace_durations)
|
||||
|
||||
def model_post_init(self, __context) -> None:
|
||||
"""Override to properly aggregate span counts from the aggregated trace data"""
|
||||
traces = getattr(self, self.trace_metrics_field_name)
|
||||
trace_ids: set[str] = set()
|
||||
|
||||
# Reset counters
|
||||
self.span_count = 0
|
||||
self.success_count = 0
|
||||
self.fail_count = 0
|
||||
self.indeterminate_count = 0
|
||||
|
||||
for trace in traces:
|
||||
if not isinstance(trace, SpanMetricsMixin):
|
||||
raise ValueError(f"Provided trace object {trace} does not implement SpanMetricsMixin.")
|
||||
|
||||
trace_ids.add(trace.trace_id)
|
||||
|
||||
# Aggregate span counts from the pre-aggregated data
|
||||
self.span_count += trace.span_count
|
||||
self.success_count += trace.success_span_count
|
||||
self.fail_count += trace.fail_span_count
|
||||
self.indeterminate_count += trace.indeterminate_span_count
|
||||
|
||||
# Check if any trace has cost data (stored or calculable)
|
||||
if hasattr(trace, 'has_cached_costs') and trace.has_cached_costs > 0:
|
||||
self.has_any_cached_costs = True
|
||||
|
||||
# Token aggregation remains the same
|
||||
self.total_tokens += trace.total_tokens
|
||||
self.success_tokens += trace.success_tokens
|
||||
self.fail_tokens += trace.fail_tokens
|
||||
|
||||
self.prompt_tokens += trace.prompt_tokens
|
||||
self.completion_tokens += trace.completion_tokens
|
||||
self.cache_read_input_tokens += trace.cache_read_input_tokens
|
||||
self.reasoning_tokens += trace.reasoning_tokens
|
||||
|
||||
self.prompt_cost += trace.prompt_cost
|
||||
self.completion_cost += trace.completion_cost
|
||||
self.total_cost += trace.total_cost
|
||||
|
||||
self._trace_metrics_additions(trace)
|
||||
|
||||
self.trace_count = len(trace_ids)
|
||||
|
||||
def _trace_metrics_additions(self, trace: ProjectMetricsTraceModel) -> None:
|
||||
"""Compute additional trace metrics for a single trace instance."""
|
||||
if trace.success:
|
||||
self.success_dates.append(trace.timestamp)
|
||||
# TODO should trace_cost_dates only be on success?
|
||||
date_cost = self.trace_cost_dates.get(trace.timestamp.date(), Decimal(0.0))
|
||||
self.trace_cost_dates[trace.timestamp.date()] = date_cost + trace.total_cost
|
||||
elif trace.fail:
|
||||
self.fail_dates.append(trace.timestamp)
|
||||
else:
|
||||
self.indeterminate_dates.append(trace.timestamp)
|
||||
|
||||
@cached_property
|
||||
def spans_per_trace(self) -> dict[int, int]:
|
||||
"""Returns a distribution of the number of spans per trace."""
|
||||
spans_per_trace: dict[int, int] = {}
|
||||
trace_span_counts: dict[int, int] = {}
|
||||
|
||||
# Use the span_count from each trace
|
||||
for trace in self.traces:
|
||||
count = trace.span_count
|
||||
trace_span_counts[count] = trace_span_counts.get(count, 0) + 1
|
||||
|
||||
# Find max count for bucket creation
|
||||
if trace_span_counts:
|
||||
max_count = max(trace_span_counts.keys())
|
||||
increment = max(1, max_count // 10)
|
||||
|
||||
for bucket_start in range(0, max_count + increment, increment):
|
||||
bucket_count = sum(
|
||||
count
|
||||
for span_count, count in trace_span_counts.items()
|
||||
if bucket_start <= span_count < bucket_start + increment
|
||||
)
|
||||
if bucket_count:
|
||||
spans_per_trace[bucket_start] = bucket_count
|
||||
|
||||
return spans_per_trace
|
||||
@@ -0,0 +1,266 @@
|
||||
from typing import Any, Optional
|
||||
from functools import cached_property
|
||||
from decimal import Decimal
|
||||
from datetime import datetime, date
|
||||
import pydantic
|
||||
|
||||
from agentops.api.db.clickhouse.models import ClickhouseAggregatedModel, SelectFields, FilterFields
|
||||
from agentops.api.models.traces import BaseTraceModel
|
||||
from agentops.api.models.metrics import (
|
||||
ProjectMetricsTraceModel,
|
||||
ProjectMetricsDurationModel,
|
||||
)
|
||||
|
||||
from .span_metrics import TraceMetricsMixin
|
||||
|
||||
|
||||
class TraceDurationWrapper(pydantic.BaseModel):
|
||||
"""Simple wrapper to maintain compatibility with existing code expecting objects with trace_duration attribute"""
|
||||
|
||||
trace_duration: int
|
||||
|
||||
|
||||
class ProjectMetricsTraceDurationBucketsModel(BaseTraceModel):
|
||||
"""
|
||||
Model representing trace duration histogram buckets for a project.
|
||||
Returns pre-aggregated histogram data instead of individual trace durations.
|
||||
"""
|
||||
|
||||
duration_bucket_ns: int
|
||||
bucket_count: int
|
||||
|
||||
@pydantic.field_validator('duration_bucket_ns', 'bucket_count', mode='before')
|
||||
@classmethod
|
||||
def ensure_int(cls, v):
|
||||
"""Ensure that values are always integers."""
|
||||
return int(v or 0)
|
||||
|
||||
@classmethod
|
||||
def _get_select_query(
|
||||
cls,
|
||||
*,
|
||||
fields: Optional[SelectFields] = None,
|
||||
filters: Optional[FilterFields] = None,
|
||||
search: Optional[str] = None,
|
||||
order_by: Optional[str] = None,
|
||||
offset: Optional[int] = None,
|
||||
limit: Optional[int] = None,
|
||||
) -> tuple[str, dict[str, Any]]:
|
||||
if fields or search or order_by or offset or limit:
|
||||
raise NotImplementedError("Custom fields, search, order_by, offset or limit are not supported.")
|
||||
|
||||
where_clause, params = cls._get_where_clause(**(filters or {}))
|
||||
|
||||
# This query creates histogram buckets for trace durations
|
||||
# We use 20 logarithmic buckets for better distribution visualization
|
||||
query = f"""
|
||||
WITH trace_durations AS (
|
||||
SELECT
|
||||
TraceId,
|
||||
toUInt64(sum(Duration)) as trace_duration
|
||||
FROM {cls.table_name}
|
||||
{f"WHERE {where_clause}" if where_clause else ""}
|
||||
GROUP BY TraceId
|
||||
),
|
||||
duration_stats AS (
|
||||
SELECT
|
||||
toUInt64(min(trace_duration)) as min_duration,
|
||||
toUInt64(max(trace_duration)) as max_duration,
|
||||
toUInt64(count()) as total_count
|
||||
FROM trace_durations
|
||||
)
|
||||
SELECT
|
||||
CASE
|
||||
WHEN total_count = 0 THEN toUInt64(0)
|
||||
WHEN min_duration = max_duration THEN min_duration
|
||||
ELSE toUInt64(floor(
|
||||
min_duration + (toFloat64(number) * toFloat64(max_duration - min_duration) / 20.0)
|
||||
))
|
||||
END as duration_bucket_ns,
|
||||
toUInt64(countIf(
|
||||
trace_duration >= CASE
|
||||
WHEN total_count = 0 THEN toUInt64(0)
|
||||
WHEN min_duration = max_duration THEN min_duration
|
||||
ELSE toUInt64(floor(min_duration + (toFloat64(number) * toFloat64(max_duration - min_duration) / 20.0)))
|
||||
END
|
||||
AND trace_duration < CASE
|
||||
WHEN total_count = 0 THEN toUInt64(1)
|
||||
WHEN min_duration = max_duration THEN min_duration + toUInt64(1)
|
||||
ELSE toUInt64(floor(min_duration + (toFloat64(number + 1) * toFloat64(max_duration - min_duration) / 20.0)))
|
||||
END
|
||||
)) as bucket_count
|
||||
FROM
|
||||
trace_durations,
|
||||
duration_stats,
|
||||
numbers(20) as number
|
||||
GROUP BY number, min_duration, max_duration, total_count
|
||||
ORDER BY duration_bucket_ns
|
||||
"""
|
||||
return query, params
|
||||
|
||||
|
||||
class ProjectMetricsDateAggregatedModel(BaseTraceModel):
|
||||
"""
|
||||
Model representing date-aggregated success/fail/indeterminate counts.
|
||||
Returns counts by date instead of individual timestamps.
|
||||
"""
|
||||
|
||||
date: date
|
||||
success_count: int
|
||||
fail_count: int
|
||||
indeterminate_count: int
|
||||
total_cost: Decimal
|
||||
|
||||
@pydantic.field_validator('success_count', 'fail_count', 'indeterminate_count', mode='before')
|
||||
@classmethod
|
||||
def ensure_int(cls, v):
|
||||
"""Ensure that counts are always integers."""
|
||||
return int(v or 0)
|
||||
|
||||
@pydantic.field_validator('total_cost', mode='before')
|
||||
@classmethod
|
||||
def ensure_decimal(cls, v):
|
||||
"""Ensure that cost is always a Decimal."""
|
||||
if isinstance(v, str):
|
||||
return Decimal(v) if v else Decimal(0)
|
||||
return Decimal(str(v)) if v else Decimal(0)
|
||||
|
||||
@classmethod
|
||||
def _get_select_query(
|
||||
cls,
|
||||
*,
|
||||
fields: Optional[SelectFields] = None,
|
||||
filters: Optional[FilterFields] = None,
|
||||
search: Optional[str] = None,
|
||||
order_by: Optional[str] = None,
|
||||
offset: Optional[int] = None,
|
||||
limit: Optional[int] = None,
|
||||
) -> tuple[str, dict[str, Any]]:
|
||||
if fields or search or order_by or offset or limit:
|
||||
raise NotImplementedError("Custom fields, search, order_by, offset or limit are not supported.")
|
||||
|
||||
where_clause, params = cls._get_where_clause(**(filters or {}))
|
||||
|
||||
# Aggregate by trace first, then by date
|
||||
query = f"""
|
||||
WITH trace_aggregates AS (
|
||||
SELECT
|
||||
TraceId,
|
||||
toDate(max(Timestamp)) as trace_date,
|
||||
argMax(StatusCode, Timestamp) as trace_status,
|
||||
sum(toDecimal64OrZero(ifNull(SpanAttributes['gen_ai.usage.total_cost'], '0'), 9)) as trace_cost
|
||||
FROM {cls.table_name}
|
||||
{f"WHERE {where_clause}" if where_clause else ""}
|
||||
GROUP BY TraceId
|
||||
)
|
||||
SELECT
|
||||
trace_date as date,
|
||||
countIf(upper(trace_status) = 'OK') as success_count,
|
||||
countIf(upper(trace_status) = 'ERROR') as fail_count,
|
||||
countIf(upper(trace_status) NOT IN ('OK', 'ERROR')) as indeterminate_count,
|
||||
sum(trace_cost) as total_cost
|
||||
FROM trace_aggregates
|
||||
GROUP BY trace_date
|
||||
ORDER BY trace_date
|
||||
"""
|
||||
return query, params
|
||||
|
||||
|
||||
class ProjectMetricsOptimizedModel(TraceMetricsMixin, ClickhouseAggregatedModel):
|
||||
"""
|
||||
Optimized model for project metrics that reduces data transfer by aggregating at the database level.
|
||||
"""
|
||||
|
||||
aggregated_models = (
|
||||
ProjectMetricsTraceModel, # Keep existing trace model for token metrics
|
||||
ProjectMetricsDurationModel, # Keep existing duration model
|
||||
ProjectMetricsTraceDurationBucketsModel, # New: histogram buckets instead of all durations
|
||||
ProjectMetricsDateAggregatedModel, # New: date aggregated counts instead of timestamps
|
||||
)
|
||||
|
||||
trace_metrics_field_name = "traces"
|
||||
|
||||
traces: list[ProjectMetricsTraceModel] = pydantic.Field(default_factory=list)
|
||||
duration: ProjectMetricsDurationModel
|
||||
trace_duration_buckets: list[ProjectMetricsTraceDurationBucketsModel] = pydantic.Field(
|
||||
default_factory=list
|
||||
)
|
||||
date_aggregates: list[ProjectMetricsDateAggregatedModel] = pydantic.Field(default_factory=list)
|
||||
|
||||
# Keep these for compatibility but they'll be populated differently
|
||||
trace_cost_dates: dict[date, Decimal] = pydantic.Field(default_factory=dict)
|
||||
success_dates: list[datetime] = pydantic.Field(default_factory=list)
|
||||
fail_dates: list[datetime] = pydantic.Field(default_factory=list)
|
||||
indeterminate_dates: list[datetime] = pydantic.Field(default_factory=list)
|
||||
trace_durations: list[TraceDurationWrapper] = pydantic.Field(default_factory=list)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
traces: list[ProjectMetricsTraceModel],
|
||||
durations: list[ProjectMetricsDurationModel],
|
||||
trace_duration_buckets: list[ProjectMetricsTraceDurationBucketsModel],
|
||||
date_aggregates: list[ProjectMetricsDateAggregatedModel],
|
||||
) -> None:
|
||||
# Call parent with modified signature
|
||||
super(ClickhouseAggregatedModel, self).__init__(
|
||||
traces=traces,
|
||||
duration=durations[0],
|
||||
trace_duration_buckets=trace_duration_buckets,
|
||||
date_aggregates=date_aggregates,
|
||||
)
|
||||
|
||||
def model_post_init(self, __context) -> None:
|
||||
"""Override to use aggregated data instead of computing from individual traces"""
|
||||
# Call parent to handle token aggregation from traces
|
||||
super().model_post_init(__context)
|
||||
|
||||
# Process date aggregates to populate date arrays
|
||||
for agg in self.date_aggregates:
|
||||
# Create datetime objects for each occurrence
|
||||
dt = datetime.combine(agg.date, datetime.min.time())
|
||||
|
||||
# Add timestamps for each count
|
||||
for _ in range(agg.success_count):
|
||||
self.success_dates.append(dt)
|
||||
for _ in range(agg.fail_count):
|
||||
self.fail_dates.append(dt)
|
||||
for _ in range(agg.indeterminate_count):
|
||||
self.indeterminate_dates.append(dt)
|
||||
|
||||
# Add to trace cost dates
|
||||
if agg.total_cost > 0:
|
||||
self.trace_cost_dates[agg.date] = agg.total_cost
|
||||
|
||||
# Convert histogram buckets to trace durations list
|
||||
# This maintains compatibility with the frontend
|
||||
for bucket in self.trace_duration_buckets:
|
||||
# Add representative durations for each bucket
|
||||
for _ in range(bucket.bucket_count):
|
||||
self.trace_durations.append(TraceDurationWrapper(trace_duration=bucket.duration_bucket_ns))
|
||||
|
||||
@cached_property
|
||||
def spans_per_trace(self) -> dict[int, int]:
|
||||
"""Returns a distribution of the number of spans per trace."""
|
||||
# This can be optimized further in a future iteration
|
||||
# For now, use the existing implementation
|
||||
spans_per_trace: dict[int, int] = {}
|
||||
trace_spans: dict[str, int] = {}
|
||||
|
||||
for trace in self.traces:
|
||||
trace_spans[trace.trace_id] = trace_spans.get(trace.trace_id, 0) + 1
|
||||
|
||||
trace_counts = trace_spans.values()
|
||||
max_count = max(trace_counts) if trace_counts else 0
|
||||
|
||||
if max_count > 0:
|
||||
increment = max_count // 10
|
||||
if increment < 1:
|
||||
increment = 1
|
||||
for index in range(0, max_count + increment, increment):
|
||||
count = sum(
|
||||
1 for count in trace_spans.values() if count >= index and count < index + increment
|
||||
)
|
||||
if count:
|
||||
spans_per_trace[index] = count
|
||||
|
||||
return spans_per_trace
|
||||
@@ -0,0 +1,426 @@
|
||||
from typing import ClassVar, Type, Any, Optional, Literal
|
||||
from decimal import Decimal
|
||||
from functools import cached_property
|
||||
import pydantic
|
||||
from tokencost import costs # type: ignore
|
||||
from agentops.api.db.clickhouse.models import (
|
||||
ClickhouseModel,
|
||||
ClickhouseAggregatedModel,
|
||||
SelectFields,
|
||||
)
|
||||
|
||||
# from .traces import (
|
||||
# TRACE_STATUS_OK,
|
||||
# TRACE_STATUS_ERROR,
|
||||
# )
|
||||
# TODO circ import
|
||||
TRACE_STATUS_OK = "OK"
|
||||
TRACE_STATUS_ERROR = "ERROR"
|
||||
|
||||
# hax to relate model names to their entries in `tokencost`
|
||||
MODEL_LOOKUP_ALIASES = {
|
||||
"sonar-pro": "perplexity/sonar-pro",
|
||||
"sonar": "perplexity/sonar",
|
||||
}
|
||||
|
||||
|
||||
def _format_cost(value: Decimal) -> str:
|
||||
"""Helper function to format a Decimal cost to a string with 7 decimal places."""
|
||||
# 7 decimal places has been observed to be adequately precise.
|
||||
return f"{float(value):.7f}"
|
||||
|
||||
|
||||
class SpanMetricsResponse(pydantic.BaseModel):
|
||||
"""
|
||||
Shared metrics response type for spans.
|
||||
"""
|
||||
|
||||
total_tokens: int
|
||||
|
||||
prompt_tokens: int
|
||||
completion_tokens: int
|
||||
cache_read_input_tokens: int
|
||||
reasoning_tokens: int
|
||||
|
||||
success_tokens: int
|
||||
fail_tokens: int
|
||||
indeterminate_tokens: int
|
||||
|
||||
prompt_cost: str
|
||||
completion_cost: str
|
||||
total_cost: str
|
||||
|
||||
@pydantic.field_validator('prompt_cost', 'completion_cost', 'total_cost', mode='before')
|
||||
@classmethod
|
||||
def format_cost(cls, v: Decimal) -> str:
|
||||
return _format_cost(v)
|
||||
|
||||
@classmethod
|
||||
def from_span_with_metrics(
|
||||
cls: Type['SpanMetricsResponse'],
|
||||
span: 'SpanMetricsMixin',
|
||||
) -> 'SpanMetricsResponse':
|
||||
"""
|
||||
Create a SpanMetricsResponse from a SpanMetricsMixin instance.
|
||||
"""
|
||||
return cls(
|
||||
total_tokens=span.total_tokens,
|
||||
prompt_tokens=span.prompt_tokens,
|
||||
completion_tokens=span.completion_tokens,
|
||||
cache_read_input_tokens=span.cache_read_input_tokens,
|
||||
reasoning_tokens=span.reasoning_tokens,
|
||||
success_tokens=span.success_tokens,
|
||||
fail_tokens=span.fail_tokens,
|
||||
indeterminate_tokens=span.indeterminate_tokens,
|
||||
# ignore these type errors because a conversion happens with field_validator
|
||||
prompt_cost=span.prompt_cost, # type: ignore
|
||||
completion_cost=span.completion_cost, # type: ignore
|
||||
total_cost=span.total_cost, # type: ignore
|
||||
)
|
||||
|
||||
|
||||
class SpanMetricsMixin(ClickhouseModel):
|
||||
status_code: str # base models must populate status_code
|
||||
trace_id: str # required for trace identification
|
||||
|
||||
request_model: Optional[str]
|
||||
response_model: Optional[str]
|
||||
|
||||
prompt_tokens: int
|
||||
completion_tokens: int
|
||||
cache_read_input_tokens: int
|
||||
reasoning_tokens: int
|
||||
cached_total_tokens: Optional[int] = None
|
||||
|
||||
cached_prompt_cost: Optional[Decimal] = None
|
||||
cached_completion_cost: Optional[Decimal] = None
|
||||
cached_total_cost: Optional[Decimal] = None
|
||||
|
||||
@classmethod
|
||||
def _get_select_clause(
|
||||
cls: Type['SpanMetricsMixin'],
|
||||
*,
|
||||
fields: Optional[SelectFields] = None,
|
||||
) -> str:
|
||||
"""Append additional metrics to the base model's selects."""
|
||||
select_clause = super(SpanMetricsMixin, cls)._get_select_clause(fields=fields)
|
||||
select_clause = f"{select_clause}, " if select_clause else ""
|
||||
|
||||
# NOTE previously we queried `llm.model` and `gent_ai.model` but it didn't
|
||||
# seems like we had any data that actually contained that so it has been removed.
|
||||
return f"""
|
||||
{select_clause}
|
||||
ifNull(SpanAttributes['gen_ai.usage.prompt_tokens'], 0) as prompt_tokens,
|
||||
ifNull(SpanAttributes['gen_ai.usage.completion_tokens'], 0) as completion_tokens,
|
||||
ifNull(SpanAttributes['gen_ai.usage.cache_read_input_tokens'], 0) as cache_read_input_tokens,
|
||||
ifNull(SpanAttributes['gen_ai.usage.reasoning_tokens'], 0) as reasoning_tokens,
|
||||
SpanAttributes['gen_ai.usage.total_tokens'] as cached_total_tokens,
|
||||
SpanAttributes['gen_ai.request.model'] as request_model,
|
||||
SpanAttributes['gen_ai.response.model'] as response_model,
|
||||
SpanAttributes['gen_ai.usage.prompt_cost'] as cached_prompt_cost,
|
||||
SpanAttributes['gen_ai.usage.completion_cost'] as cached_completion_cost,
|
||||
SpanAttributes['gen_ai.usage.total_cost'] as cached_total_cost
|
||||
"""
|
||||
|
||||
@pydantic.field_validator(
|
||||
'prompt_tokens',
|
||||
'completion_tokens',
|
||||
'cache_read_input_tokens',
|
||||
'reasoning_tokens',
|
||||
mode='before',
|
||||
)
|
||||
@classmethod
|
||||
def ensure_int(cls, v: Any) -> int:
|
||||
"""Ensure that all token counts are always an integer."""
|
||||
return int(v or 0)
|
||||
|
||||
@pydantic.field_validator('cached_total_tokens', mode='before')
|
||||
@classmethod
|
||||
def ensure_int_or_none(cls, v: Any) -> Optional[int]:
|
||||
"""Ensure token counts are int when present."""
|
||||
if v is None or v == "":
|
||||
return None
|
||||
|
||||
return int(v)
|
||||
|
||||
@pydantic.field_validator(
|
||||
'cached_prompt_cost',
|
||||
'cached_completion_cost',
|
||||
'cached_total_cost',
|
||||
mode='before',
|
||||
)
|
||||
@classmethod
|
||||
def ensure_decimal(cls, v: Any) -> Optional[Decimal]:
|
||||
"""Ensure that cached costs are always a Decimal."""
|
||||
if v is None:
|
||||
return None
|
||||
|
||||
if isinstance(v, Decimal):
|
||||
return v # Already a Decimal, return as-is
|
||||
|
||||
if isinstance(v, str) and v: # filter empty strings
|
||||
return Decimal(v)
|
||||
|
||||
if isinstance(v, (int, float)):
|
||||
return Decimal(str(v)) # convert to string to avoid float precision issues
|
||||
|
||||
return None
|
||||
|
||||
@pydantic.field_validator('trace_id', 'status_code', mode='before')
|
||||
@classmethod
|
||||
def ensure_required(cls, v: Any) -> Any:
|
||||
"""Ensure that the trace_id and status_code are always present."""
|
||||
if not v:
|
||||
raise ValueError(f"Required field cannot be empty: {cls.__name__}.{v}")
|
||||
return v
|
||||
|
||||
@property
|
||||
def success(self) -> bool:
|
||||
"""Indicates whether the trace was successful based on its status code."""
|
||||
return self.status_code == TRACE_STATUS_OK
|
||||
|
||||
@property
|
||||
def fail(self) -> bool:
|
||||
"""Indicates whether the trace failed based on its status code."""
|
||||
return self.status_code == TRACE_STATUS_ERROR
|
||||
|
||||
@property
|
||||
def indeterminate(self) -> bool:
|
||||
"""Indicates whether the trace is indeterminate (i.e., not successful or failed)."""
|
||||
return self.status_code not in (TRACE_STATUS_OK, TRACE_STATUS_ERROR)
|
||||
|
||||
@cached_property # this might actually be slower
|
||||
def total_tokens(self) -> int:
|
||||
"""
|
||||
Returns the total tokens used in the span. This is the sum of all token types.
|
||||
"""
|
||||
if self.cached_total_tokens is not None:
|
||||
# if the SDK has populated this value, assume it's correct.
|
||||
return self.cached_total_tokens
|
||||
|
||||
return (
|
||||
self.prompt_tokens + self.completion_tokens + self.cache_read_input_tokens + self.reasoning_tokens
|
||||
)
|
||||
|
||||
@property
|
||||
def success_tokens(self) -> int:
|
||||
"""Number of successful tokens."""
|
||||
return self.total_tokens if self.success else 0
|
||||
|
||||
@property
|
||||
def fail_tokens(self) -> int:
|
||||
"""Number of failed tokens."""
|
||||
return self.total_tokens if self.fail else 0
|
||||
|
||||
@property
|
||||
def indeterminate_tokens(self) -> int:
|
||||
"""Number of indeterminate tokens."""
|
||||
return self.total_tokens if self.indeterminate else 0
|
||||
|
||||
@property
|
||||
def model_for_cost(self) -> Optional[str]:
|
||||
"""Get the best available model for calculating costs."""
|
||||
model_name: Optional[str] = None
|
||||
|
||||
if self.response_model:
|
||||
# often we have both a request and a response model set, in this case
|
||||
# the response model will have been converted by the provider SDK to
|
||||
# include specifics about it's release version.
|
||||
model_name = self.response_model
|
||||
else:
|
||||
# otherwise return the request model which is essentially user input,
|
||||
# or `None` if there is no model information.
|
||||
model_name = self.request_model
|
||||
|
||||
# sometimes we have see model names that don't correspond to the records
|
||||
# in `tokencost` so we convert them here.
|
||||
if model_name in MODEL_LOOKUP_ALIASES:
|
||||
model_name = MODEL_LOOKUP_ALIASES[model_name]
|
||||
|
||||
return model_name
|
||||
|
||||
@cached_property
|
||||
def prompt_cost(self) -> Decimal:
|
||||
"""The cost of the prompt based on the tokens and model used."""
|
||||
# TODO we need to incorporate cached tokens where they apply.
|
||||
if self.cached_prompt_cost is not None:
|
||||
# precalculated cost from the collector
|
||||
return self.cached_prompt_cost
|
||||
|
||||
return self._calculate_cost(self.prompt_tokens, "input")
|
||||
|
||||
@cached_property
|
||||
def completion_cost(self) -> Decimal:
|
||||
"""The cost of the completion based on the tokens and model used."""
|
||||
# TODO we need to incorporate reasoning tokens where they apply.
|
||||
if self.cached_completion_cost is not None:
|
||||
# precalculated cost from the collector
|
||||
return self.cached_completion_cost
|
||||
|
||||
return self._calculate_cost(self.completion_tokens, "output")
|
||||
|
||||
@property
|
||||
def total_cost(self) -> Decimal:
|
||||
"""Returns the total cost of the trace, which is the sum of the prompt and completion costs."""
|
||||
if self.cached_total_cost is not None:
|
||||
# precalculated cost from the SDK
|
||||
return self.cached_total_cost
|
||||
|
||||
return self.prompt_cost + self.completion_cost
|
||||
|
||||
def _calculate_cost(self, tokens: int, direction: Literal["input", "output"]) -> Decimal:
|
||||
"""Calculate the cost of the input or output tokens for the span's model."""
|
||||
if not self.model_for_cost:
|
||||
return Decimal(0)
|
||||
|
||||
try:
|
||||
completion_cost = costs.calculate_cost_by_tokens(tokens, self.model_for_cost, direction)
|
||||
except Exception:
|
||||
return Decimal(0)
|
||||
|
||||
if not completion_cost:
|
||||
return Decimal(0)
|
||||
|
||||
return completion_cost
|
||||
|
||||
|
||||
class TraceMetricsResponse(pydantic.BaseModel):
|
||||
"""
|
||||
Trace metrics response model used in trace detail responses.
|
||||
"""
|
||||
|
||||
span_count: int
|
||||
trace_count: int
|
||||
success_count: int
|
||||
fail_count: int
|
||||
indeterminate_count: int
|
||||
|
||||
prompt_tokens: int
|
||||
completion_tokens: int
|
||||
cache_read_input_tokens: int
|
||||
reasoning_tokens: int
|
||||
total_tokens: int
|
||||
|
||||
prompt_cost: str
|
||||
completion_cost: str
|
||||
average_cost_per_trace: str
|
||||
total_cost: str
|
||||
|
||||
@pydantic.field_validator(
|
||||
'prompt_cost', 'completion_cost', 'average_cost_per_trace', 'total_cost', mode='before'
|
||||
)
|
||||
@classmethod
|
||||
def format_cost(cls, v: Decimal) -> str:
|
||||
return _format_cost(v)
|
||||
|
||||
@classmethod
|
||||
def from_trace_with_metrics(
|
||||
cls: Type['TraceMetricsResponse'],
|
||||
trace: 'TraceMetricsMixin',
|
||||
) -> 'TraceMetricsResponse':
|
||||
"""
|
||||
Create a TraceMetricsResponse from a TraceMetricsMixin instance.
|
||||
"""
|
||||
return cls(
|
||||
span_count=trace.span_count,
|
||||
trace_count=trace.trace_count,
|
||||
success_count=trace.success_count,
|
||||
fail_count=trace.fail_count,
|
||||
indeterminate_count=trace.indeterminate_count,
|
||||
prompt_tokens=trace.prompt_tokens,
|
||||
completion_tokens=trace.completion_tokens,
|
||||
cache_read_input_tokens=trace.cache_read_input_tokens,
|
||||
reasoning_tokens=trace.reasoning_tokens,
|
||||
total_tokens=trace.total_tokens,
|
||||
# ignore these type errors because a conversion happens with field_validator
|
||||
prompt_cost=trace.prompt_cost, # type: ignore
|
||||
completion_cost=trace.completion_cost, # type: ignore
|
||||
average_cost_per_trace=trace.average_cost_per_trace, # type: ignore
|
||||
total_cost=trace.total_cost, # type: ignore
|
||||
)
|
||||
|
||||
|
||||
class TraceMetricsMixin(ClickhouseAggregatedModel):
|
||||
trace_metrics_field_name: ClassVar[str] = "traces"
|
||||
|
||||
span_count: int = 0
|
||||
trace_count: int = 0
|
||||
success_count: int = 0
|
||||
fail_count: int = 0
|
||||
indeterminate_count: int = 0
|
||||
|
||||
total_tokens: int = 0
|
||||
success_tokens: int = 0
|
||||
fail_tokens: int = 0
|
||||
|
||||
prompt_tokens: int = 0
|
||||
completion_tokens: int = 0
|
||||
cache_read_input_tokens: int = 0
|
||||
reasoning_tokens: int = 0
|
||||
|
||||
prompt_cost: Decimal = Decimal(0)
|
||||
completion_cost: Decimal = Decimal(0)
|
||||
total_cost: Decimal = Decimal(0)
|
||||
|
||||
def model_post_init(self, __context) -> None:
|
||||
"""Compute all trace metrics once during initialization to avoid repeated loops"""
|
||||
traces = getattr(self, self.trace_metrics_field_name)
|
||||
trace_ids: set[str] = set()
|
||||
|
||||
for trace in traces:
|
||||
if not isinstance(trace, SpanMetricsMixin):
|
||||
raise ValueError(f"Provided trace object {trace} does not implement SpanMetricsMixin.")
|
||||
|
||||
trace_ids.add(trace.trace_id)
|
||||
|
||||
if trace.success:
|
||||
self.success_count += 1
|
||||
elif trace.fail:
|
||||
self.fail_count += 1
|
||||
else:
|
||||
self.indeterminate_count += 1
|
||||
|
||||
self.total_tokens += trace.total_tokens
|
||||
self.success_tokens += trace.success_tokens
|
||||
self.fail_tokens += trace.fail_tokens
|
||||
|
||||
self.prompt_tokens += trace.prompt_tokens
|
||||
self.completion_tokens += trace.completion_tokens
|
||||
self.cache_read_input_tokens += trace.cache_read_input_tokens
|
||||
self.reasoning_tokens += trace.reasoning_tokens
|
||||
|
||||
self.prompt_cost += trace.prompt_cost
|
||||
self.completion_cost += trace.completion_cost
|
||||
self.total_cost += trace.total_cost
|
||||
|
||||
self._trace_metrics_additions(trace)
|
||||
|
||||
self.span_count = len(traces)
|
||||
self.trace_count = len(trace_ids)
|
||||
|
||||
def _trace_metrics_additions(self, trace: Any) -> None:
|
||||
"""
|
||||
Helper method to add a single trace's metrics to the current instance.
|
||||
This prevents us from having to repeat the loop.
|
||||
"""
|
||||
pass
|
||||
|
||||
@property
|
||||
def avg_tokens(self) -> float:
|
||||
"""Returns the average tokens per trace"""
|
||||
return self.total_tokens / self.span_count if self.span_count > 0 else 0.0
|
||||
|
||||
@property
|
||||
def avg_success_tokens(self) -> float:
|
||||
"""Returns the average tokens for successful traces"""
|
||||
return self.success_tokens / self.success_count if self.success_count > 0 else 0.0
|
||||
|
||||
@property
|
||||
def avg_fail_tokens(self) -> float:
|
||||
"""Returns the average tokens for failed traces"""
|
||||
return self.fail_tokens / self.fail_count if self.fail_count > 0 else 0.0
|
||||
|
||||
@property
|
||||
def average_cost_per_trace(self) -> Decimal:
|
||||
"""Returns the average cost per trace"""
|
||||
return self.total_cost / self.trace_count if self.trace_count > 0 else Decimal(0)
|
||||
@@ -0,0 +1,475 @@
|
||||
from typing import Any, Optional, Type
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
import pydantic
|
||||
from decimal import Decimal
|
||||
|
||||
from agentops.api.db.clickhouse.models import (
|
||||
ClickhouseModel,
|
||||
TClickhouseModel,
|
||||
ClickhouseAggregatedModel,
|
||||
SelectFields,
|
||||
FilterFields,
|
||||
WithinListOperation,
|
||||
)
|
||||
|
||||
from .span_metrics import SpanMetricsMixin, TraceMetricsMixin
|
||||
|
||||
|
||||
TRACE_STATUS_OK = "OK"
|
||||
TRACE_STATUS_ERROR = "ERROR"
|
||||
|
||||
|
||||
def nanosecond_timedelta(ns: int) -> timedelta:
|
||||
"""Return a timedelta object from nanoseconds."""
|
||||
seconds = ns // 1_000_000_000
|
||||
microseconds = (ns % 1_000_000_000) // 1000 # Convert remaining ns to μs
|
||||
return timedelta(seconds=seconds, microseconds=microseconds)
|
||||
|
||||
|
||||
class BaseTraceModel(ClickhouseModel):
|
||||
"""
|
||||
BaseTraceModel is a base model for the trace data in Clickhouse.
|
||||
|
||||
This model defines the structure of the trace data and is used to interact with
|
||||
the `otel_traces` table in Clickhouse.
|
||||
|
||||
This class is inherited from by other models that interact with the `otel_traces`
|
||||
table, so it is kept free of attributes to allow them to be defined for each use case.
|
||||
|
||||
Field lookups and filters are common to all models that interact with this table,
|
||||
so they are shared here in this base class.
|
||||
"""
|
||||
|
||||
table_name = "otel_traces"
|
||||
selectable_fields = {
|
||||
'Timestamp': "timestamp",
|
||||
'project_id': "project_id",
|
||||
'TraceId': "trace_id",
|
||||
'SpanId': "span_id",
|
||||
'ParentSpanId': "parent_span_id",
|
||||
'TraceState': "trace_state",
|
||||
'SpanName': "span_name",
|
||||
'SpanKind': "span_kind",
|
||||
'ServiceName': "service_name",
|
||||
'ResourceAttributes': "resource_attributes",
|
||||
'ScopeName': "scope_name",
|
||||
'ScopeVersion': "scope_version",
|
||||
'SpanAttributes': "span_attributes",
|
||||
"SpanAttributes['agentops.tags']": "tags",
|
||||
'Duration': "duration",
|
||||
'StatusCode': "status_code",
|
||||
'StatusMessage': "status_message",
|
||||
'Events.Timestamp': "event_timestamps",
|
||||
'Events.Name': "event_names",
|
||||
'Events.Attributes': "event_attributes",
|
||||
'Links.TraceId': "link_trace_ids",
|
||||
'Links.SpanId': "link_span_ids",
|
||||
'Links.TraceState': "link_trace_states",
|
||||
'Links.Attributes': "link_attributes",
|
||||
}
|
||||
filterable_fields = {
|
||||
"trace_id": ("=", "TraceId"),
|
||||
"span_id": ("=", "SpanId"),
|
||||
"parent_span_id": ("=", "ParentSpanId"),
|
||||
"project_id": ("=", "project_id"),
|
||||
"project_ids": (WithinListOperation, "project_id"),
|
||||
"start_time": (">=", "Timestamp"),
|
||||
"end_time": ("<=", "Timestamp"),
|
||||
}
|
||||
|
||||
@pydantic.field_validator('status_code', check_fields=False, mode='before')
|
||||
@classmethod
|
||||
def uppercase_status(cls, v: str) -> str:
|
||||
"""Ensure status_code is always uppercase (if it is present)."""
|
||||
return v.upper()
|
||||
|
||||
@pydantic.field_validator('tags', check_fields=False, mode='before')
|
||||
@classmethod
|
||||
def parse_tags_json(cls, value: str) -> list[str]:
|
||||
"""Parse the tags JSON string into a list of tags."""
|
||||
try:
|
||||
return json.loads(value)
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
|
||||
class SpanModel(SpanMetricsMixin, BaseTraceModel):
|
||||
"""
|
||||
SpanModel represents a single span within a trace. This model is used to retrieve
|
||||
span data from the `otel_traces` table in Clickhouse.
|
||||
|
||||
Incorporates `SpanMetricsMixin` to handle token calculations.
|
||||
"""
|
||||
|
||||
project_id: str
|
||||
trace_id: str
|
||||
span_id: str
|
||||
parent_span_id: Optional[str] = None
|
||||
|
||||
timestamp: datetime
|
||||
duration: int
|
||||
status_code: str
|
||||
status_message: Optional[str] = None
|
||||
|
||||
trace_state: Optional[str] = None
|
||||
span_name: Optional[str] = None
|
||||
span_kind: Optional[str] = None
|
||||
service_name: Optional[str] = None
|
||||
scope_name: Optional[str] = None
|
||||
scope_version: Optional[str] = None
|
||||
tags: Optional[list[str]] = pydantic.Field(default_factory=list)
|
||||
|
||||
resource_attributes: dict[str, Any]
|
||||
span_attributes: dict[str, Any]
|
||||
|
||||
event_timestamps: list[datetime] = pydantic.Field(default_factory=list)
|
||||
event_names: list[str] = pydantic.Field(default_factory=list)
|
||||
event_attributes: list[Any] = pydantic.Field(default_factory=list)
|
||||
|
||||
link_trace_ids: list[str] = pydantic.Field(default_factory=list)
|
||||
link_span_ids: list[str] = pydantic.Field(default_factory=list)
|
||||
link_trace_states: list[str] = pydantic.Field(default_factory=list)
|
||||
link_attributes: list[Any] = pydantic.Field(default_factory=list)
|
||||
|
||||
@property
|
||||
def start_time(self) -> datetime:
|
||||
"""start_time property returns the timestamp of the span."""
|
||||
return self.timestamp.astimezone(timezone.utc)
|
||||
|
||||
@property
|
||||
def end_time(self) -> datetime:
|
||||
"""Determine the end time of the span based on the start time and duration."""
|
||||
return self.start_time + nanosecond_timedelta(self.duration)
|
||||
|
||||
|
||||
class TraceModel(TraceMetricsMixin, ClickhouseAggregatedModel):
|
||||
"""
|
||||
TraceModel is an aggregate model that actually only queries one model, but
|
||||
having the aggregate as a parent gives us a place to store the trace metrics.
|
||||
"""
|
||||
|
||||
aggregated_models = (SpanModel,)
|
||||
|
||||
trace_metrics_field_name = "spans"
|
||||
|
||||
spans: list[SpanModel] = pydantic.Field(default_factory=list)
|
||||
|
||||
def __init__(self, spans: list[SpanModel]) -> None:
|
||||
super().__init__(
|
||||
spans=spans,
|
||||
)
|
||||
|
||||
@property
|
||||
def trace_id(self) -> str:
|
||||
"""
|
||||
Get the trace ID for this group of spans.
|
||||
Validates that all spans in the trace have the same trace ID (they always
|
||||
should) and returns it.
|
||||
"""
|
||||
trace_ids = {span.trace_id for span in self.spans}
|
||||
assert len(trace_ids) == 1, "All spans in a trace are expected to have the same trace_id"
|
||||
return trace_ids.pop()
|
||||
|
||||
@property
|
||||
def project_id(self) -> str:
|
||||
"""
|
||||
Get the project ID for this group of spans.
|
||||
|
||||
Validates that all spans in the trace have the same project ID (they
|
||||
always should) and returns it.
|
||||
"""
|
||||
project_ids = {span.project_id for span in self.spans}
|
||||
assert len(project_ids) == 1, "All spans in a trace are expected to have the same project_id"
|
||||
return project_ids.pop()
|
||||
|
||||
@property
|
||||
def start_time(self) -> datetime:
|
||||
"""Get the start time of the trace from the first span."""
|
||||
return min(span.start_time for span in self.spans)
|
||||
|
||||
@property
|
||||
def end_time(self) -> datetime:
|
||||
"""Get the end time of the trace from the last span."""
|
||||
return max(span.end_time for span in self.spans)
|
||||
|
||||
@property
|
||||
def tags(self) -> list[str]:
|
||||
"""Get tags from the root span."""
|
||||
# the SDK currently only sets tags on the root span and we always have at least one span
|
||||
return self.spans[0].tags
|
||||
|
||||
|
||||
class TraceSummaryModel(BaseTraceModel):
|
||||
"""
|
||||
TraceListModel represents a summary of traces in Clickhouse grouped by `trace_id`.
|
||||
|
||||
This model is used to interact with the `otel_traces` table in Clickhouse to retrieve
|
||||
a list of traces with summary information suitable for use in a list view.
|
||||
"""
|
||||
|
||||
filterable_fields = {
|
||||
"project_id": ("=", "project_id"),
|
||||
"start_time": (">=", "Timestamp"),
|
||||
"end_time": ("<=", "Timestamp"),
|
||||
}
|
||||
searchable_fields = {
|
||||
# searchable field should reference the alias we create in the sub-select
|
||||
"trace_id": ("ILIKE", "trace_id"),
|
||||
"span_name": ("ILIKE", "span_name"),
|
||||
"tags": ("ILIKE", "tags"),
|
||||
}
|
||||
|
||||
trace_id: str
|
||||
service_name: Optional[str] = None
|
||||
span_name: Optional[str] = None
|
||||
start_time: datetime
|
||||
duration: int
|
||||
span_count: int
|
||||
error_count: int
|
||||
tags: Optional[list[str]] = pydantic.Field(default_factory=list)
|
||||
total_cost: Optional[float] = None
|
||||
|
||||
@pydantic.field_validator('start_time', mode='before')
|
||||
def datetime_with_timezone(cls, v: datetime) -> datetime:
|
||||
"""Ensure the start_time is formatted as ISO strings."""
|
||||
return v.astimezone(timezone.utc)
|
||||
|
||||
@property
|
||||
def end_time(self) -> datetime:
|
||||
"""Determine the end time of the span based on the start time and duration."""
|
||||
return self.start_time + nanosecond_timedelta(self.duration)
|
||||
|
||||
@classmethod
|
||||
def _get_select_query(
|
||||
cls: Type[TClickhouseModel],
|
||||
*,
|
||||
fields: Optional[SelectFields] = None,
|
||||
filters: Optional[FilterFields] = None,
|
||||
search: Optional[str] = None,
|
||||
order_by: str = "start_time ASC",
|
||||
offset: int = 0,
|
||||
limit: int = 20,
|
||||
) -> tuple[str, dict[str, Any]]:
|
||||
if fields:
|
||||
raise NotImplementedError("`TraceListModel.select` does not support `fields`")
|
||||
|
||||
where_clause, where_params = cls._get_where_clause(**(filters or {}))
|
||||
having_clause, having_params = cls._get_search_clause(search)
|
||||
params = {**where_params, **having_params}
|
||||
|
||||
# we use `argMin` on the aggregation because we can assume that the oldest
|
||||
# span is the root span
|
||||
query = f"""
|
||||
WITH traces AS
|
||||
(
|
||||
SELECT
|
||||
TraceId as trace_id,
|
||||
any(ServiceName) AS service_name,
|
||||
argMin(SpanName, Timestamp) AS span_name,
|
||||
argMin(SpanAttributes['agentops.tags'], Timestamp) AS tags,
|
||||
-- Calculate wall-clock duration instead of summing individual span durations
|
||||
min(Timestamp) AS start_time,
|
||||
-- Use the difference between the earliest span start and the latest span start to approximate total elapsed time in nanoseconds
|
||||
dateDiff('nanosecond', min(Timestamp), max(Timestamp)) AS duration,
|
||||
count() AS span_count,
|
||||
countIf(upper(StatusCode) = '{TRACE_STATUS_ERROR}') AS error_count,
|
||||
-- Sum up total cost from all spans in the trace
|
||||
-- Use hybrid approach: stored costs when available, calculated costs otherwise
|
||||
sum(
|
||||
if(
|
||||
SpanAttributes['gen_ai.usage.total_cost'] != '',
|
||||
toFloat64OrZero(SpanAttributes['gen_ai.usage.total_cost']),
|
||||
toFloat64(
|
||||
calculate_prompt_cost(
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.prompt_tokens'], '0')),
|
||||
coalesce(
|
||||
nullIf(SpanAttributes['gen_ai.response.model'], ''),
|
||||
nullIf(SpanAttributes['gen_ai.request.model'], '')
|
||||
)
|
||||
) + calculate_completion_cost(
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.completion_tokens'], '0')),
|
||||
coalesce(
|
||||
nullIf(SpanAttributes['gen_ai.response.model'], ''),
|
||||
nullIf(SpanAttributes['gen_ai.request.model'], '')
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
) AS total_cost
|
||||
FROM {cls.table_name}
|
||||
{f"WHERE {where_clause}" if where_clause else ""}
|
||||
GROUP BY trace_id
|
||||
)
|
||||
SELECT *
|
||||
FROM traces
|
||||
{f"HAVING {having_clause}" if having_clause else ""}
|
||||
ORDER BY {order_by}
|
||||
LIMIT {limit}
|
||||
OFFSET {offset}
|
||||
"""
|
||||
return query, params
|
||||
|
||||
|
||||
class TraceListMetricsModel(SpanMetricsMixin, BaseTraceModel):
|
||||
"""
|
||||
Returns statistics related to trace counts for a given project. This model is used to
|
||||
interact with the `otel_traces` table in Clickhouse to retrieve aggregate trace counts
|
||||
for use in supporting a trace list view.
|
||||
|
||||
Note that while the `TraceSummaryModel` this is paired with returns a subset of the
|
||||
available traces, this model references all applicable traces (based on the shared
|
||||
filters) and can be used to display the metrics for the entire dataset.
|
||||
|
||||
Implements hybrid cost calculation: uses stored costs when available, calculates
|
||||
on-the-fly for historical data. This approach was inspired by FoxyAI's needs.
|
||||
"""
|
||||
|
||||
selectable_fields = {
|
||||
"TraceId": "trace_id",
|
||||
'StatusCode': "status_code",
|
||||
}
|
||||
filterable_fields = {
|
||||
"project_id": ("=", "project_id"),
|
||||
"start_time": (">=", "Timestamp"),
|
||||
"end_time": ("<=", "Timestamp"),
|
||||
"span_name": ("ILIKE", "SpanName"),
|
||||
}
|
||||
searchable_fields = {
|
||||
# searchable field should reference the columns in the table
|
||||
"trace_id": ("ILIKE", "TraceId"),
|
||||
"span_name": ("ILIKE", "SpanName"),
|
||||
"tags": ("ILIKE", "SpanAttributes['agentops.tags']"),
|
||||
}
|
||||
|
||||
# Add aggregated fields
|
||||
trace_id: str
|
||||
status_code: str
|
||||
span_count: int = 1
|
||||
prompt_tokens: int = 0
|
||||
completion_tokens: int = 0
|
||||
cache_read_input_tokens: int = 0
|
||||
reasoning_tokens: int = 0
|
||||
cached_total_cost: Decimal = Decimal(0)
|
||||
|
||||
@pydantic.field_validator(
|
||||
'span_count',
|
||||
'prompt_tokens',
|
||||
'completion_tokens',
|
||||
'cache_read_input_tokens',
|
||||
'reasoning_tokens',
|
||||
mode='before',
|
||||
)
|
||||
@classmethod
|
||||
def ensure_int(cls, v: Any) -> int:
|
||||
"""Ensure that all counts are always an integer."""
|
||||
return int(v or 0)
|
||||
|
||||
@pydantic.field_validator('cached_total_cost', mode='before')
|
||||
@classmethod
|
||||
def ensure_decimal(cls, v: Any) -> Decimal:
|
||||
"""Ensure that cost is always a Decimal."""
|
||||
if isinstance(v, str):
|
||||
return Decimal(v) if v else Decimal(0)
|
||||
return Decimal(str(v)) if v else Decimal(0)
|
||||
|
||||
@classmethod
|
||||
def _get_select_query(
|
||||
cls: Type[TClickhouseModel],
|
||||
*,
|
||||
fields: Optional[SelectFields] = None,
|
||||
filters: Optional[FilterFields] = None,
|
||||
search: Optional[str] = None,
|
||||
order_by: str = "start_time ASC",
|
||||
offset: int = 0,
|
||||
limit: int = 20,
|
||||
) -> tuple[str, dict[str, Any]]:
|
||||
"""
|
||||
Aggregate trace metrics at the database level for performance.
|
||||
|
||||
For costs: Uses stored total_cost when available, calculates on-the-fly for missing data.
|
||||
This preserves 100% accurate costs for new data while fixing historical gaps.
|
||||
"""
|
||||
if fields:
|
||||
raise NotImplementedError("`TraceListMetricsModel.select` does not support `fields`")
|
||||
|
||||
# Get the where clause from parent
|
||||
where_clause, params = cls._get_where_clause(**(filters or {}))
|
||||
|
||||
# Apply search conditions if provided
|
||||
if search:
|
||||
search_conditions = []
|
||||
search_value = f"%{search}%"
|
||||
for field, (operator, column) in cls.searchable_fields.items():
|
||||
if operator == "ILIKE":
|
||||
search_conditions.append(f"{column} ILIKE %(search_{field})s")
|
||||
params[f"search_{field}"] = search_value
|
||||
|
||||
if search_conditions:
|
||||
search_clause = f"({' OR '.join(search_conditions)})"
|
||||
where_clause = f"{where_clause} AND {search_clause}" if where_clause else search_clause
|
||||
|
||||
# Aggregate by trace at the database level - this is the key optimization
|
||||
query = f"""
|
||||
SELECT
|
||||
TraceId as trace_id,
|
||||
argMax(StatusCode, Timestamp) as status_code,
|
||||
count() as span_count,
|
||||
sum(toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.prompt_tokens'], '0'))) as prompt_tokens,
|
||||
sum(toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.completion_tokens'], '0'))) as completion_tokens,
|
||||
sum(toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.cache_read_input_tokens'], '0'))) as cache_read_input_tokens,
|
||||
sum(toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.reasoning_tokens'], '0'))) as reasoning_tokens,
|
||||
any(SpanAttributes['gen_ai.request.model']) as request_model,
|
||||
any(SpanAttributes['gen_ai.response.model']) as response_model,
|
||||
sum(
|
||||
if(
|
||||
SpanAttributes['gen_ai.usage.total_cost'] != '',
|
||||
toDecimal64OrZero(SpanAttributes['gen_ai.usage.total_cost'], 9),
|
||||
toDecimal64(
|
||||
calculate_prompt_cost(
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.prompt_tokens'], '0')),
|
||||
coalesce(
|
||||
nullIf(SpanAttributes['gen_ai.response.model'], ''),
|
||||
nullIf(SpanAttributes['gen_ai.request.model'], '')
|
||||
)
|
||||
) + calculate_completion_cost(
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.completion_tokens'], '0')),
|
||||
coalesce(
|
||||
nullIf(SpanAttributes['gen_ai.response.model'], ''),
|
||||
nullIf(SpanAttributes['gen_ai.request.model'], '')
|
||||
)
|
||||
),
|
||||
9
|
||||
)
|
||||
)
|
||||
) as cached_total_cost
|
||||
FROM {cls.table_name}
|
||||
{f"WHERE {where_clause}" if where_clause else ""}
|
||||
GROUP BY TraceId
|
||||
"""
|
||||
|
||||
return query, params
|
||||
|
||||
|
||||
class TraceListModel(TraceMetricsMixin, ClickhouseAggregatedModel):
|
||||
"""
|
||||
TraceListModel is an aggregate model that combines the results of `TraceSummaryModel`
|
||||
and `TraceListMetricsModel` to provide a list of traces matching the user query
|
||||
for a subset of traces, along with aggregate metrics for the entire trace set.
|
||||
"""
|
||||
|
||||
aggregated_models = (
|
||||
TraceSummaryModel,
|
||||
TraceListMetricsModel,
|
||||
)
|
||||
|
||||
trace_metrics_field_name = "metrics_traces"
|
||||
|
||||
traces: list[TraceSummaryModel] = pydantic.Field(default_factory=list)
|
||||
metrics_traces: list[TraceListMetricsModel] = pydantic.Field(default_factory=list)
|
||||
|
||||
def __init__(self, traces: list[TraceSummaryModel], metrics_traces: list[TraceListMetricsModel]) -> None:
|
||||
super().__init__(
|
||||
traces=traces,
|
||||
metrics_traces=metrics_traces,
|
||||
)
|
||||
@@ -0,0 +1,55 @@
|
||||
import httpx
|
||||
import os
|
||||
import asyncio
|
||||
|
||||
from .log_config import logger
|
||||
|
||||
API_KEY = os.environ.get("PROMPTARMOR_API_KEY")
|
||||
|
||||
|
||||
async def evaluate(prompt, session_id: str, mode: str, source=None, destination=None) -> bool:
|
||||
"""
|
||||
Evaluate a prompt with the PromptArmor API.
|
||||
Args:
|
||||
prompt: the content that you are sending to an LLM
|
||||
session_id: the session id for set of calls to the LLM
|
||||
mode: the mode of the evaluation. Either "input" or "output"
|
||||
source(optional) : the source of this content that you are sending to the LLM
|
||||
destination (optional) : the destination of this output that will come from the LLM
|
||||
Returns (bool):
|
||||
The response from the API. {"containsInjection":true}
|
||||
"""
|
||||
if mode not in ["input", "output"]:
|
||||
raise ValueError("mode must be either 'input' or 'output'")
|
||||
|
||||
if mode == "input":
|
||||
url = "https://api.aidr.promptarmor.com/v1/analyze/input"
|
||||
else:
|
||||
url = "https://api.aidr.promptarmor.com/v1/analyze/output"
|
||||
|
||||
promptarmor_headers = {
|
||||
"PromptArmor-Auth": f"Bearer {API_KEY}",
|
||||
# The session ID is unique to each user session(e.g. a workflow or conversation)
|
||||
"PromptArmor-Session-ID": session_id,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
data = {"content": prompt, "source": source, "destination": destination}
|
||||
|
||||
async with httpx.AsyncClient() as async_client:
|
||||
response = await async_client.post(url, headers=promptarmor_headers, json=data)
|
||||
|
||||
return response.json().get("detection", None)
|
||||
|
||||
|
||||
async def get_promptarmor_flag(prompt, completion, session_id) -> bool | None:
|
||||
"TODO: Implement other specific flags https://promptarmor.readme.io/reference/v1analyzeinput"
|
||||
try:
|
||||
input_check, output_check = await asyncio.gather(
|
||||
evaluate(prompt, session_id, mode="input"),
|
||||
evaluate(completion, session_id, mode="output"),
|
||||
)
|
||||
return input_check or output_check
|
||||
except Exception as e:
|
||||
logger.warning(f"Unable to get Promptarmor Flag: {e}")
|
||||
return None
|
||||
@@ -0,0 +1,338 @@
|
||||
import asyncio
|
||||
from decimal import Decimal
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
import agentops.api.event_handlers as event_handlers
|
||||
import agentops.api.interactors.spans as span_handlers
|
||||
from agentops.api.db.supabase_client import AsyncSupabaseClient
|
||||
from agentops.api.exceptions import InvalidModelError
|
||||
from agentops.api.log_config import logger
|
||||
from agentops.api.utils import update_stats
|
||||
|
||||
# Create a router for v1 endpoints
|
||||
router = APIRouter(prefix="/v1")
|
||||
|
||||
|
||||
@router.post("/sessions")
|
||||
async def create_session(request: Request, supabase: AsyncSupabaseClient):
|
||||
"""Create a new session"""
|
||||
try:
|
||||
api_key = request.headers.get("X-Agentops-Auth")
|
||||
parent_key = request.headers.get("X-Agentops-Parent-Key")
|
||||
|
||||
tasks = [
|
||||
supabase.table("projects").select("id").eq("api_key", api_key).limit(1).single().execute(),
|
||||
request.json(),
|
||||
]
|
||||
|
||||
if parent_key:
|
||||
tasks.append(
|
||||
supabase.table("projects").select("id").eq("api_key", parent_key).limit(1).single().execute()
|
||||
)
|
||||
project, data, project_secondary = await asyncio.gather(*tasks)
|
||||
else:
|
||||
project, data = await asyncio.gather(*tasks)
|
||||
project_secondary = None
|
||||
|
||||
logger.debug(data)
|
||||
|
||||
if project is None:
|
||||
raise RuntimeError("Invalid API Key")
|
||||
|
||||
except RuntimeError as e:
|
||||
message = {"message": f"/sessions: Error posting session: {e}"}
|
||||
logger.error(message)
|
||||
return JSONResponse(message, status_code=401)
|
||||
|
||||
try:
|
||||
session = {
|
||||
"id": data["session"]["session_id"],
|
||||
"project_id": project["id"],
|
||||
"init_timestamp": data["session"]["init_timestamp"],
|
||||
"end_timestamp": data["session"].get("end_timestamp", None),
|
||||
"tags": data["session"].get("tags", None),
|
||||
"end_state": data["session"].get("end_state", None),
|
||||
"end_state_reason": data["session"].get("end_state_reason", None),
|
||||
"video": data["session"].get("video", None),
|
||||
"host_env": data["session"].get("host_env", None),
|
||||
}
|
||||
|
||||
if project_secondary:
|
||||
session["project_id_secondary"] = project_secondary["id"]
|
||||
|
||||
await supabase.table("sessions").upsert(session).execute()
|
||||
await supabase.table("stats").upsert({"session_id": session["id"]}).execute()
|
||||
|
||||
cost = await (
|
||||
supabase.table("stats").select("cost").eq("session_id", session["id"]).limit(1).single().execute()
|
||||
)
|
||||
|
||||
logger.info(f"/session: Completed POST request for {session['id']}")
|
||||
if cost is not None:
|
||||
return JSONResponse(
|
||||
{
|
||||
"status": "success",
|
||||
"token_cost": cost.get("cost", "0.00") or "0.00",
|
||||
}
|
||||
)
|
||||
return JSONResponse({"status": "success"})
|
||||
except RuntimeError as e:
|
||||
message = {"message": f"/sessions: Error posting session: {e}"}
|
||||
logger.error(message)
|
||||
return JSONResponse(message, status_code=400)
|
||||
|
||||
|
||||
@router.post("/agents")
|
||||
async def agents(request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
api_key = request.headers.get("X-Agentops-Auth")
|
||||
|
||||
sessions, data = await asyncio.gather(
|
||||
supabase.table("sessions").select("id").eq("api_key", api_key).limit(1).single().execute(),
|
||||
request.json(),
|
||||
)
|
||||
|
||||
session_ids = [session["id"] for session in sessions]
|
||||
if data["session_id"] not in session_ids:
|
||||
raise RuntimeError("Invalid API Key for Session")
|
||||
|
||||
logger.debug(data)
|
||||
|
||||
except RuntimeError as e:
|
||||
message = {"message": f"/agents: Error creating agent: {e}"}
|
||||
logger.error(message)
|
||||
return JSONResponse(message, status_code=401)
|
||||
|
||||
try:
|
||||
agent = {
|
||||
"id": data["id"],
|
||||
"session_id": data["session_id"],
|
||||
"name": data.get("name", None),
|
||||
"logs": data.get("logs", None),
|
||||
}
|
||||
|
||||
await supabase.table("agents").upsert(agent).execute()
|
||||
|
||||
logger.info(f"/agents: Completed POST request for {agent['id']}")
|
||||
return JSONResponse("Success")
|
||||
except RuntimeError as e:
|
||||
message = {"message": f"/agents: Error creating agent: {e}"}
|
||||
logger.error(message)
|
||||
return JSONResponse(message, status_code=400)
|
||||
|
||||
|
||||
@router.post("/threads")
|
||||
async def threads(request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
api_key = request.headers.get("X-Agentops-Auth")
|
||||
|
||||
sessions, data = await asyncio.gather(
|
||||
supabase.table("sessions").select("id").eq("api_key", api_key).limit(1).single().execute(),
|
||||
request.json(),
|
||||
)
|
||||
|
||||
session_ids = [session["id"] for session in sessions]
|
||||
if data["threads"]["session_id"] not in session_ids:
|
||||
raise RuntimeError("Invalid API Key for Session")
|
||||
|
||||
logger.debug(data)
|
||||
|
||||
except RuntimeError as e:
|
||||
message = {"message": f"/threads: Error creating thread: {e}"}
|
||||
logger.error(message)
|
||||
return JSONResponse(message, status_code=401)
|
||||
|
||||
try:
|
||||
thread = {
|
||||
"id": data["threads"]["id"],
|
||||
"session_id": data["threads"]["session_id"],
|
||||
"agent_id": data["threads"].get("agent_id", None),
|
||||
}
|
||||
|
||||
await supabase.table("threads").upsert(thread).execute()
|
||||
|
||||
logger.info(f"/threads: Completed POST request for {thread['id']}")
|
||||
return JSONResponse("Success")
|
||||
except RuntimeError as e:
|
||||
message = {"message": f"/threads: Error creating agent: {e}"}
|
||||
logger.error(message)
|
||||
return JSONResponse(message, status_code=400)
|
||||
|
||||
|
||||
@router.post("/events")
|
||||
async def events(request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
api_key = request.headers.get("X-Agentops-Auth")
|
||||
|
||||
sessions, data = await asyncio.gather(
|
||||
supabase.table("sessions").select("id").eq("api_key", api_key).limit(1).single().execute(),
|
||||
request.json(),
|
||||
)
|
||||
# premium_status = await get_premium_status(supabase, sessions['id'])
|
||||
premium_status = False
|
||||
|
||||
session_id = data.get("session_id")
|
||||
session_ids_for_project = [session["id"] for session in sessions]
|
||||
if session_id not in session_ids_for_project:
|
||||
raise RuntimeError("Invalid API Key for session")
|
||||
|
||||
except RuntimeError as e:
|
||||
message = {"message": f"/events: Error posting event: {e}"}
|
||||
logger.error(message)
|
||||
return JSONResponse(message, status_code=401)
|
||||
|
||||
except InvalidModelError as e:
|
||||
message = {"message": f"/events: Invalid model while posting event: {e}"}
|
||||
return JSONResponse(message, status_code=401)
|
||||
|
||||
try:
|
||||
actions = []
|
||||
llms = []
|
||||
tools = []
|
||||
errors = []
|
||||
additional_cost: Decimal | None = Decimal(0)
|
||||
additional_events = 0
|
||||
additional_prompt_tokens = 0
|
||||
additional_completion_tokens = 0
|
||||
for event in data.get("events"):
|
||||
additional_events += 1
|
||||
if event["event_type"] == "llms":
|
||||
llm = await event_handlers.handle_llms(event, premium_status, session_id)
|
||||
cost = llm.get("cost")
|
||||
if cost is not None:
|
||||
additional_cost += Decimal(cost)
|
||||
additional_prompt_tokens += llm["prompt_tokens"]
|
||||
additional_completion_tokens += llm["completion_tokens"]
|
||||
llms.append(llm)
|
||||
elif event["event_type"] == "tools":
|
||||
tools.append(await event_handlers.handle_tools(event, session_id))
|
||||
# TODO: move into an /errors endpoint?
|
||||
elif event["event_type"] == "errors":
|
||||
errors.append(await event_handlers.handle_errors(event, session_id))
|
||||
else:
|
||||
actions.append(await event_handlers.handle_actions(event, session_id))
|
||||
|
||||
if additional_cost == Decimal(0):
|
||||
additional_cost = None
|
||||
|
||||
inserts = []
|
||||
if len(actions) != 0:
|
||||
inserts.append(supabase.table("actions").upsert(actions).execute())
|
||||
if len(llms) != 0:
|
||||
inserts.append(supabase.table("llms").upsert(llms).execute())
|
||||
if len(tools) != 0:
|
||||
inserts.append(supabase.table("tools").upsert(tools).execute())
|
||||
if len(errors) != 0:
|
||||
inserts.append(supabase.table("errors").upsert(errors).execute())
|
||||
|
||||
inserts.append(
|
||||
update_stats(
|
||||
supabase=supabase,
|
||||
session_id=session_id,
|
||||
cost=additional_cost,
|
||||
events=additional_events,
|
||||
prompt_tokens=additional_prompt_tokens,
|
||||
completion_tokens=additional_completion_tokens,
|
||||
errors=len(errors),
|
||||
)
|
||||
)
|
||||
if inserts:
|
||||
results = await asyncio.gather(*inserts, return_exceptions=True)
|
||||
runtime_errors = [result for result in results if isinstance(result, Exception)]
|
||||
if len(runtime_errors) > 0:
|
||||
raise RuntimeError(runtime_errors[0])
|
||||
|
||||
logger.info(f"/events: Completed POST request for {api_key}")
|
||||
return JSONResponse("Success")
|
||||
except RuntimeError as e:
|
||||
message = {"message": f"/events: Error posting event: {e}"}
|
||||
logger.error(message)
|
||||
return JSONResponse(message, status_code=400)
|
||||
|
||||
|
||||
@router.post("/developer_errors")
|
||||
async def developer_errors(request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.debug(data)
|
||||
|
||||
developer_error = {
|
||||
"api_key": request.headers.get("X-Agentops-Auth"),
|
||||
"session_id": data.get("session_id", None),
|
||||
"sdk_version": data.get("sdk_version", None),
|
||||
"type": data.get("type", None),
|
||||
"message": data.get("message", None),
|
||||
"stack_trace": data.get("stack_trace", None),
|
||||
"host_env": data.get("host_env", None),
|
||||
}
|
||||
|
||||
await supabase.table("developer_errors").upsert(developer_error).execute()
|
||||
logger.info(f"/developer_errors: Completed POST request for {request.headers.get('X-Agentops-Auth')}")
|
||||
return JSONResponse("", status_code=204)
|
||||
except RuntimeError as e:
|
||||
message = {"message": f"/developer_errors: Error posting developer_error: {e}"}
|
||||
logger.error(message)
|
||||
return JSONResponse(message, status_code=400)
|
||||
|
||||
|
||||
@router.post("/traces")
|
||||
async def traces(request: Request, supabase: AsyncSupabaseClient):
|
||||
"""Ingest OpenTelemetry spans"""
|
||||
try:
|
||||
api_key = request.headers.get("X-Agentops-Auth")
|
||||
|
||||
sessions, data = await asyncio.gather(
|
||||
supabase.table("sessions").select("id").eq("api_key", api_key).limit(1).single().execute(),
|
||||
request.json(),
|
||||
)
|
||||
|
||||
session_id = data.get("session_id")
|
||||
session_ids_for_project = [session["id"] for session in sessions]
|
||||
if session_id not in session_ids_for_project:
|
||||
raise RuntimeError("Invalid API Key for session")
|
||||
|
||||
logger.debug(data)
|
||||
|
||||
except RuntimeError as e:
|
||||
message = {"message": f"/traces: Error processing spans: {e}"}
|
||||
logger.error(message)
|
||||
return JSONResponse(message, status_code=401)
|
||||
|
||||
try:
|
||||
spans_data = []
|
||||
for span in data.get("spans", []):
|
||||
# Classify the span
|
||||
span_type = await span_handlers.classify_span(span)
|
||||
|
||||
# Route to the appropriate handler
|
||||
if span_type == span_handlers.SESSION_UPDATE_SPAN:
|
||||
span_data = await span_handlers.handle_session_update_span(span, session_id)
|
||||
elif span_type == span_handlers.GEN_AI_SPAN:
|
||||
span_data = await span_handlers.handle_gen_ai_span(span, session_id)
|
||||
elif span_type == span_handlers.LOG_SPAN:
|
||||
span_data = await span_handlers.handle_log_span(span, session_id)
|
||||
else:
|
||||
# Default to session update handler
|
||||
span_data = await span_handlers.handle_session_update_span(span, session_id)
|
||||
|
||||
spans_data.append(span_data)
|
||||
|
||||
# Insert spans into the database
|
||||
if spans_data:
|
||||
await supabase.table("spans").upsert(spans_data).execute()
|
||||
|
||||
logger.info(f"/traces: Completed POST request for {api_key}")
|
||||
return JSONResponse({"status": "success"})
|
||||
except RuntimeError as e:
|
||||
message = {"message": f"/traces: Error processing spans: {e}"}
|
||||
logger.error(message)
|
||||
return JSONResponse(message, status_code=400)
|
||||
|
||||
|
||||
# @router.get("/openapi.yaml")
|
||||
# async def openapi_yaml(request: Request):
|
||||
# with open("openapi-spec.yaml", "r") as f:
|
||||
# content = f.read()
|
||||
# return Response(content=content, media_type="text/yaml")
|
||||
@@ -0,0 +1,852 @@
|
||||
import asyncio
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from decimal import Decimal
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from termcolor import colored
|
||||
|
||||
from agentops.common.environment import APP_URL
|
||||
import agentops.api.event_handlers as event_handlers
|
||||
from agentops.api.db.supabase_client import AsyncSupabaseClient
|
||||
from agentops.api.exceptions import ExpiredJWTError, InvalidModelError, InvalidAPIKeyError
|
||||
from agentops.api.log_config import logger
|
||||
from agentops.api.utils import generate_jwt, update_stats, validate_uuid, verify_jwt
|
||||
|
||||
from agentops.exporter import export
|
||||
|
||||
# Create a router for v2 endpoints
|
||||
router = APIRouter(prefix="/v2")
|
||||
|
||||
jwt_secret = os.environ["JWT_SECRET_KEY"]
|
||||
app_url = APP_URL
|
||||
|
||||
|
||||
|
||||
@router.post("/sessions")
|
||||
async def create_session(request: Request, supabase: AsyncSupabaseClient):
|
||||
"""Create a new session"""
|
||||
try:
|
||||
api_key = request.headers.get("X-Agentops-Api-Key")
|
||||
parent_key = request.headers.get("X-Agentops-Parent-Key")
|
||||
|
||||
validate_uuid(api_key)
|
||||
tasks = [
|
||||
supabase.table("projects").select("*").eq("api_key", api_key).limit(1).single().execute(),
|
||||
request.json(),
|
||||
]
|
||||
|
||||
if parent_key:
|
||||
tasks.append(
|
||||
supabase.table("projects").select("*").eq("api_key", parent_key).limit(1).single().execute()
|
||||
)
|
||||
project, data, project_secondary = await asyncio.gather(*tasks)
|
||||
else:
|
||||
project, data = await asyncio.gather(*tasks)
|
||||
project_secondary = None
|
||||
|
||||
logger.debug(data)
|
||||
|
||||
if project is None:
|
||||
raise RuntimeError("Invalid API Key")
|
||||
|
||||
session = {
|
||||
"id": data["session"]["session_id"],
|
||||
"project_id": project["id"],
|
||||
"init_timestamp": data["session"]["init_timestamp"],
|
||||
"end_timestamp": data["session"].get("end_timestamp", None),
|
||||
"tags": data["session"].get("tags", None),
|
||||
"end_state": data["session"].get("end_state", None),
|
||||
"end_state_reason": data["session"].get("end_state_reason", None),
|
||||
"video": data["session"].get("video", None),
|
||||
"host_env": data["session"].get("host_env", None),
|
||||
}
|
||||
|
||||
if project_secondary:
|
||||
session["project_id_secondary"] = project_secondary["id"]
|
||||
|
||||
await supabase.table("sessions").insert(session).execute()
|
||||
await supabase.table("stats").insert({"session_id": session["id"]}).execute()
|
||||
await export.create_session(session)
|
||||
|
||||
token = generate_jwt(session["id"], jwt_secret)
|
||||
logger.info(colored(f"Completed request for {session['id']}", "yellow"))
|
||||
return JSONResponse(
|
||||
{
|
||||
"status": "Success",
|
||||
"jwt": token,
|
||||
"session_url": f'{app_url}/drilldown?session_id={data["session"]["session_id"]}',
|
||||
},
|
||||
status_code=200,
|
||||
)
|
||||
except ExpiredJWTError:
|
||||
logger.warning("Expired JWT")
|
||||
return JSONResponse({"path": request.url.path, "message": "Expired Token"}, status_code=401)
|
||||
except InvalidAPIKeyError as e:
|
||||
# This is a user error (invalid API key format), not a system error
|
||||
# Log as warning to avoid Sentry alerts
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.warning(
|
||||
f"{request.url.path}: Invalid API key format for session {data.get('session', {}).get('session_id', 'unknown')}"
|
||||
)
|
||||
except Exception:
|
||||
logger.warning(f"{request.url.path}: Invalid API key format")
|
||||
|
||||
return JSONResponse(
|
||||
{
|
||||
"path": request.url.path,
|
||||
"message": "Invalid API key format",
|
||||
},
|
||||
status_code=400,
|
||||
)
|
||||
except RuntimeError as e:
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.error(
|
||||
f"{request.url.path}: Error creating session with id {data['session']['session_id']}: {e} Data received: {data}"
|
||||
)
|
||||
except Exception as log_error:
|
||||
logger.error(f"{request.url.path}: Error creating session: {e} Could not read data: {log_error}")
|
||||
|
||||
return JSONResponse(
|
||||
{
|
||||
"path": request.url.path,
|
||||
"message": f"Error creating session: {e}",
|
||||
},
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/reauthorize_jwt")
|
||||
async def v2_reauthorize_jwt(request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
api_key = request.headers.get("X-Agentops-Api-Key")
|
||||
|
||||
validate_uuid(api_key)
|
||||
|
||||
tasks = [
|
||||
supabase.table("projects").select("id").eq("api_key", api_key).execute(),
|
||||
request.json(),
|
||||
]
|
||||
project_response, data = await asyncio.gather(*tasks)
|
||||
|
||||
project = project_response.data[0] if project_response.data else None
|
||||
|
||||
if project is None:
|
||||
raise RuntimeError("Invalid API Key")
|
||||
|
||||
session_response = (
|
||||
await supabase.table("sessions").select("project_id").eq("id", data["session_id"]).execute()
|
||||
)
|
||||
session = session_response.data[0] if session_response.data else None
|
||||
|
||||
if session is None:
|
||||
raise RuntimeError("Invalid Session Id")
|
||||
|
||||
if session["project_id"] != project["id"]:
|
||||
raise RuntimeError("Invalid Session Id")
|
||||
|
||||
token = generate_jwt(data["session_id"], jwt_secret)
|
||||
logger.info(colored(f"Completed request for session: {data['session_id']}", "yellow"))
|
||||
return JSONResponse({"status": "Success", "jwt": token})
|
||||
|
||||
except InvalidAPIKeyError as e:
|
||||
# This is a user error (invalid API key format), not a system error
|
||||
# Log as warning to avoid Sentry alerts
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.warning(
|
||||
f"{request.url.path}: Invalid API key format for session {data.get('session', {}).get('session_id', 'unknown')}"
|
||||
)
|
||||
except Exception:
|
||||
logger.warning(f"{request.url.path}: Invalid API key format")
|
||||
|
||||
return JSONResponse(
|
||||
{
|
||||
"path": request.url.path,
|
||||
"message": "Invalid API key format",
|
||||
},
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
|
||||
except RuntimeError as e:
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.error(f"{request.url.path}: Error reauthorizing Api Key: {e} Data received: {data}")
|
||||
except Exception as log_error:
|
||||
logger.error(
|
||||
f"{request.url.path}: Error reauthorizing Api Key: {e} Could not read data: {log_error}"
|
||||
)
|
||||
|
||||
return JSONResponse(
|
||||
{
|
||||
"path": request.url.path,
|
||||
"message": f" Error reauthorizing Api Key: {e}",
|
||||
},
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/create_session")
|
||||
async def v2_create_session(request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
api_key = request.headers.get("X-Agentops-Api-Key")
|
||||
parent_key = request.headers.get("X-Agentops-Parent-Key")
|
||||
|
||||
validate_uuid(api_key)
|
||||
|
||||
tasks = [
|
||||
supabase.table("projects").select("id").eq("api_key", api_key).execute(),
|
||||
request.json(),
|
||||
]
|
||||
|
||||
if parent_key:
|
||||
tasks.append(supabase.table("projects").select("id").eq("api_key", parent_key).execute())
|
||||
project_response, data, project_secondary_response = await asyncio.gather(*tasks)
|
||||
project_secondary = (
|
||||
project_secondary_response.data[0] if project_secondary_response.data else None
|
||||
)
|
||||
else:
|
||||
project_response, data = await asyncio.gather(*tasks)
|
||||
project_secondary = None
|
||||
|
||||
project = project_response.data[0] if project_response.data else None
|
||||
|
||||
logger.debug(data)
|
||||
|
||||
if project is None:
|
||||
raise RuntimeError("Invalid API Key")
|
||||
|
||||
session = {
|
||||
"id": data["session"]["session_id"],
|
||||
"project_id": project["id"],
|
||||
"init_timestamp": data["session"].get("init_timestamp", None)
|
||||
or datetime.now(timezone.utc).isoformat(),
|
||||
"end_timestamp": data["session"].get("end_timestamp", None),
|
||||
"tags": data["session"].get("tags", None),
|
||||
"end_state": data["session"].get("end_state", None),
|
||||
"end_state_reason": data["session"].get("end_state_reason", None),
|
||||
"video": data["session"].get("video", None),
|
||||
"host_env": data["session"].get("host_env", None),
|
||||
}
|
||||
|
||||
if project_secondary:
|
||||
session["project_id_secondary"] = project_secondary["id"]
|
||||
|
||||
await supabase.table("sessions").insert(session).execute()
|
||||
await supabase.table("stats").insert({"session_id": session["id"]}).execute()
|
||||
await export.create_session(session)
|
||||
|
||||
token = generate_jwt(session["id"], jwt_secret)
|
||||
logger.info(colored(f"Completed request for {session['id']}", "yellow"))
|
||||
return JSONResponse(
|
||||
{
|
||||
"status": "Success",
|
||||
"jwt": token,
|
||||
"session_url": f'{app_url}/drilldown?session_id={data["session"]["session_id"]}',
|
||||
}
|
||||
)
|
||||
except ExpiredJWTError:
|
||||
logger.warning("Expired JWT")
|
||||
return JSONResponse({"path": str(request.url.path), "message": "Expired Token"}, status_code=401)
|
||||
except InvalidAPIKeyError as e:
|
||||
# This is a user error (invalid API key format), not a system error
|
||||
# Log as warning to avoid Sentry alerts
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.warning(
|
||||
f"{request.url.path}: Invalid API key format for session {data.get('session', {}).get('session_id', 'unknown')}"
|
||||
)
|
||||
except Exception:
|
||||
logger.warning(f"{request.url.path}: Invalid API key format")
|
||||
|
||||
return JSONResponse(
|
||||
{
|
||||
"path": request.url.path,
|
||||
"message": "Invalid API key format",
|
||||
},
|
||||
status_code=400,
|
||||
)
|
||||
except RuntimeError as e:
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.error(
|
||||
f"{request.url.path}: Error creating session with id {data['session']['session_id']}: {e} Data received: {data}"
|
||||
)
|
||||
except Exception as log_error:
|
||||
logger.error(f"{request.url.path}: Error creating session: {e} Could not read data: {log_error}")
|
||||
|
||||
return JSONResponse(
|
||||
{
|
||||
"path": str(request.url.path),
|
||||
"message": f"Error creating session: {e}",
|
||||
},
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/update_session")
|
||||
async def v2_update_session(request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
authorization_header = request.headers.get("Authorization")
|
||||
if authorization_header is None:
|
||||
raise RuntimeError("Bearer Token is Missing")
|
||||
|
||||
token = authorization_header.split(" ")[1]
|
||||
session_id = verify_jwt(token, jwt_secret)
|
||||
data = await request.json()
|
||||
|
||||
logger.debug(data)
|
||||
|
||||
session = {
|
||||
"id": session_id,
|
||||
"init_timestamp": data["session"]["init_timestamp"],
|
||||
"end_timestamp": data["session"].get("end_timestamp", None),
|
||||
"tags": data["session"].get("tags", None),
|
||||
"end_state": data["session"].get("end_state", None),
|
||||
"end_state_reason": data["session"].get("end_state_reason", None),
|
||||
"video": data["session"].get("video", None),
|
||||
"host_env": data["session"].get("host_env", None),
|
||||
}
|
||||
|
||||
await supabase.table("sessions").update(session).eq("id", session_id).execute()
|
||||
await export.update_session(session)
|
||||
|
||||
cost_response = await supabase.table("stats").select("cost").eq("session_id", session_id).execute()
|
||||
cost = cost_response.data[0] if cost_response.data else None
|
||||
|
||||
logger.info(colored(f"Completed request for session: {session_id}", "yellow"))
|
||||
if cost is not None:
|
||||
return JSONResponse(
|
||||
{
|
||||
"status": "success",
|
||||
"token_cost": cost.get("cost", "0.00") or "0.00",
|
||||
"session_url": f"{app_url}/drilldown?session_id={session_id}",
|
||||
}
|
||||
)
|
||||
return JSONResponse({"status": "success"})
|
||||
except ExpiredJWTError:
|
||||
logger.warning("Expired JWT")
|
||||
return JSONResponse({"path": str(request.url.path), "message": "Expired Token"}, status_code=401)
|
||||
except RuntimeError as e:
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.error(f"{request.url.path}: Error posting session: {e} Data received: {data}")
|
||||
except Exception as log_error:
|
||||
logger.error(f"{request.url.path}: Error posting session: {e} Could not read data: {log_error}")
|
||||
|
||||
return JSONResponse(
|
||||
{
|
||||
"path": str(request.url.path),
|
||||
"message": f"Error posting session: {e}",
|
||||
},
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/create_agent")
|
||||
async def v2_create_agent(request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
authorization_header = request.headers.get("Authorization")
|
||||
if authorization_header is None:
|
||||
raise RuntimeError("Bearer Token is Missing")
|
||||
|
||||
token = authorization_header.split(" ")[1]
|
||||
session_id = verify_jwt(token, jwt_secret)
|
||||
data = await request.json()
|
||||
|
||||
logger.debug(data)
|
||||
|
||||
agent = {
|
||||
"id": data["id"],
|
||||
"session_id": session_id,
|
||||
"name": data.get("name", None),
|
||||
"logs": data.get("logs", None),
|
||||
}
|
||||
|
||||
await supabase.table("agents").upsert(agent).execute()
|
||||
await export.create_agent(agent)
|
||||
|
||||
logger.info(
|
||||
colored(
|
||||
f"Completed request request for agent {agent['id']} and session {session_id}",
|
||||
"yellow",
|
||||
)
|
||||
)
|
||||
return JSONResponse("Success")
|
||||
except ExpiredJWTError:
|
||||
logger.warning("Expired JWT")
|
||||
return JSONResponse({"path": request.url.path, "message": "Expired Token"}, status_code=401)
|
||||
except RuntimeError as e:
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.error(f"{request.url.path}: Error creating agent: {e} Data received: {data}")
|
||||
except Exception as log_error:
|
||||
logger.error(f"{request.url.path}: Error creating agent: {e} Could not read data: {log_error}")
|
||||
|
||||
return JSONResponse(
|
||||
{
|
||||
"path": request.url.path,
|
||||
"message": f"Error creating agent: {e}",
|
||||
},
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/create_thread")
|
||||
async def v2_create_thread(request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
authorization_header = request.headers.get("Authorization")
|
||||
if authorization_header is None:
|
||||
raise RuntimeError("Bearer Token is Missing")
|
||||
|
||||
token = authorization_header.split(" ")[1]
|
||||
session_id = verify_jwt(token, jwt_secret)
|
||||
data = await request.json()
|
||||
|
||||
logger.debug(data)
|
||||
|
||||
thread = {
|
||||
"id": data["id"],
|
||||
"session_id": session_id,
|
||||
"agent_id": data.get("agent_id", None),
|
||||
}
|
||||
|
||||
await supabase.table("threads").upsert(thread).execute()
|
||||
|
||||
logger.info(colored(f"Completed request request for thread: {thread['id']}", "yellow"))
|
||||
return JSONResponse("Success")
|
||||
except ExpiredJWTError:
|
||||
logger.warning("Expired JWT")
|
||||
return JSONResponse({"path": request.url.path, "message": "Expired Token"}, status_code=401)
|
||||
except RuntimeError as e:
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.error(f"{request.url.path}: Error creating agent: {e} Data received: {data}")
|
||||
except Exception as log_error:
|
||||
logger.error(f"{request.url.path}: Error creating agent: {e} Could not read data: {log_error}")
|
||||
|
||||
return JSONResponse(
|
||||
{
|
||||
"path": request.url.path,
|
||||
"message": f"Error creating agent: {e}",
|
||||
},
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/create_events")
|
||||
async def v2_create_events(request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
authorization_header = request.headers.get("Authorization")
|
||||
if authorization_header is None:
|
||||
raise RuntimeError("Bearer Token is Missing")
|
||||
|
||||
token = authorization_header.split(" ")[1]
|
||||
session_id = verify_jwt(token, jwt_secret)
|
||||
data = await request.json()
|
||||
|
||||
# premium_status = await get_premium_status(supabase, sessions['id'])
|
||||
premium_status = False
|
||||
|
||||
actions = []
|
||||
llms = []
|
||||
tools = []
|
||||
errors = []
|
||||
additional_cost: Decimal | None = Decimal(0)
|
||||
additional_events = 0
|
||||
additional_prompt_tokens = 0
|
||||
additional_completion_tokens = 0
|
||||
for event in data.get("events"):
|
||||
additional_events += 1
|
||||
if event["event_type"] == "llms":
|
||||
llm = await event_handlers.handle_llms(event, premium_status, session_id)
|
||||
cost = llm.get("cost")
|
||||
if cost is not None:
|
||||
additional_cost += Decimal(cost)
|
||||
additional_prompt_tokens += llm["prompt_tokens"]
|
||||
additional_completion_tokens += llm["completion_tokens"]
|
||||
llms.append(llm)
|
||||
elif event["event_type"] == "tools":
|
||||
tools.append(await event_handlers.handle_tools(event, session_id))
|
||||
elif event["event_type"] == "errors":
|
||||
errors.append(await event_handlers.handle_errors(event, session_id))
|
||||
else:
|
||||
actions.append(await event_handlers.handle_actions(supabase, event, session_id))
|
||||
|
||||
if additional_cost == Decimal(0):
|
||||
additional_cost = None
|
||||
|
||||
inserts = []
|
||||
if len(actions) != 0:
|
||||
inserts.append(supabase.table("actions").insert(actions).execute())
|
||||
for action in actions:
|
||||
await export.create_action_event(action)
|
||||
if len(llms) != 0:
|
||||
inserts.append(supabase.table("llms").insert(llms).execute())
|
||||
for llm in llms:
|
||||
await export.create_llm_event(llm)
|
||||
if len(tools) != 0:
|
||||
inserts.append(supabase.table("tools").insert(tools).execute())
|
||||
for tool in tools:
|
||||
await export.create_tool_event(tool)
|
||||
if len(errors) != 0:
|
||||
inserts.append(supabase.table("errors").insert(errors).execute())
|
||||
for error in errors:
|
||||
await export.create_error_event(error)
|
||||
|
||||
inserts.append(
|
||||
update_stats(
|
||||
supabase=supabase,
|
||||
session_id=session_id,
|
||||
cost=additional_cost,
|
||||
events=additional_events,
|
||||
prompt_tokens=additional_prompt_tokens,
|
||||
completion_tokens=additional_completion_tokens,
|
||||
errors=len(errors),
|
||||
)
|
||||
)
|
||||
|
||||
if inserts:
|
||||
results = await asyncio.gather(*inserts, return_exceptions=True)
|
||||
runtime_errors = [result for result in results if isinstance(result, Exception)]
|
||||
if len(runtime_errors) > 0:
|
||||
raise RuntimeError(runtime_errors[0])
|
||||
|
||||
logger.info(colored(f"Completed request request for Session: {session_id}", "yellow"))
|
||||
return JSONResponse("Success")
|
||||
except ExpiredJWTError:
|
||||
logger.warning("Expired JWT")
|
||||
return JSONResponse({"path": request.url.path, "message": "Expired Token"}, status_code=401)
|
||||
except InvalidModelError as e:
|
||||
message = {
|
||||
"path": request.url.path,
|
||||
"message": f"Invalid model while posting event: {e}",
|
||||
}
|
||||
return JSONResponse(message, status_code=401)
|
||||
except RuntimeError as e:
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.error(f"{request.url.path}: Error posting event: {e} Data received: {data}")
|
||||
except Exception as log_error:
|
||||
logger.error(f"{request.url.path}: Error posting event: {e} Could not read data: {log_error}")
|
||||
|
||||
return JSONResponse(
|
||||
{"path": request.url.path, "message": f"Error posting event: {e}"},
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/update_events")
|
||||
async def v2_update_events(request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
authorization_header = request.headers.get("Authorization")
|
||||
if authorization_header is None:
|
||||
raise RuntimeError("Bearer Token is Missing")
|
||||
|
||||
token = authorization_header.split(" ")[1]
|
||||
session_id = verify_jwt(token, jwt_secret)
|
||||
data = await request.json()
|
||||
|
||||
# premium_status = await get_premium_status(supabase, sessions['id'])
|
||||
premium_status = False
|
||||
|
||||
actions = []
|
||||
llms = []
|
||||
tools = []
|
||||
errors = []
|
||||
for event in data.get("events"):
|
||||
if event["event_type"] == "llms":
|
||||
llm = await event_handlers.handle_llms(event, premium_status, session_id)
|
||||
llms.append(llm)
|
||||
elif event["event_type"] == "tools":
|
||||
tools.append(await event_handlers.handle_tools(event, session_id))
|
||||
elif event["event_type"] == "errors":
|
||||
errors.append(await event_handlers.handle_errors(event, session_id))
|
||||
else:
|
||||
actions.append(await event_handlers.handle_actions(supabase, event, session_id))
|
||||
|
||||
inserts = []
|
||||
for action in actions:
|
||||
inserts.append(supabase.table("actions").update(action).eq("id", action.get("id")).execute())
|
||||
await export.update_action_event(action)
|
||||
for llm in llms:
|
||||
inserts.append(supabase.table("llms").update(llm).eq("id", llm.get("id")).execute())
|
||||
await export.update_llm_event(llm)
|
||||
for tool in tools:
|
||||
inserts.append(supabase.table("tools").update(tool).eq("id", tool.get("id")).execute())
|
||||
await export.update_tool_event(tool)
|
||||
for error in errors:
|
||||
inserts.append(supabase.table("errors").update(error).eq("id", error.get("id")).execute())
|
||||
await export.update_error_event(error)
|
||||
|
||||
if inserts:
|
||||
results = await asyncio.gather(*inserts, return_exceptions=True)
|
||||
runtime_errors = [result for result in results if isinstance(result, RuntimeError)]
|
||||
if len(runtime_errors) > 0:
|
||||
raise RuntimeError(runtime_errors)
|
||||
|
||||
logger.info(colored(f"Completed request request for Session: {session_id}", "yellow"))
|
||||
return JSONResponse("Success")
|
||||
except ExpiredJWTError:
|
||||
logger.warning("Expired JWT")
|
||||
return JSONResponse({"path": request.url.path, "message": "Expired Token"}, status_code=401)
|
||||
except InvalidModelError as e:
|
||||
message = {
|
||||
"path": request.url.path,
|
||||
"message": f"Invalid model while posting event: {e}",
|
||||
}
|
||||
return JSONResponse(message, status_code=401)
|
||||
except RuntimeError as e:
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.error(f"{request.url.path}: Error posting event: {e} Data received: {data}")
|
||||
except Exception as log_error:
|
||||
logger.error(f"{request.url.path}: Error posting event: {e} Could not read data: {log_error}")
|
||||
|
||||
return JSONResponse(
|
||||
{"path": request.url.path, "message": f"Error posting event: {e}"},
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
|
||||
@router.put("/update_logs")
|
||||
async def v2_update_logs(request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
authorization_header = request.headers.get("Authorization")
|
||||
if authorization_header is None:
|
||||
raise RuntimeError("Bearer Token is Missing")
|
||||
|
||||
token = authorization_header.split(" ")[1]
|
||||
session_id = verify_jwt(token, jwt_secret)
|
||||
data = await request.json()
|
||||
|
||||
if "logs" not in data:
|
||||
raise RuntimeError("Logs data is missing")
|
||||
|
||||
# Store logs in Supabase Storage
|
||||
bucket_name = "session-logs"
|
||||
file_path = f"{session_id}.txt"
|
||||
|
||||
# Get the project_id
|
||||
session_response = (
|
||||
await supabase.table("sessions").select("project_id").eq("id", session_id).execute()
|
||||
)
|
||||
session = session_response.data[0] if session_response.data else None
|
||||
|
||||
if not session:
|
||||
raise RuntimeError("Session not found")
|
||||
|
||||
project_id = session["project_id"]
|
||||
|
||||
# Create the logs content
|
||||
logs_content = data["logs"]
|
||||
|
||||
# Append to existing logs in Supabase Storage
|
||||
storage_client = supabase.storage.from_(bucket_name)
|
||||
|
||||
# Check if file exists
|
||||
try:
|
||||
existing_file = await storage_client.download(f"{project_id}/{file_path}")
|
||||
existing_content = existing_file.decode("utf-8")
|
||||
new_content = existing_content + logs_content
|
||||
except:
|
||||
# File doesn't exist yet
|
||||
new_content = logs_content
|
||||
|
||||
# Upload the file
|
||||
await storage_client.upload(f"{project_id}/{file_path}", new_content.encode("utf-8"))
|
||||
|
||||
# Get the public URL
|
||||
public_url = storage_client.get_public_url(f"{project_id}/{file_path}")
|
||||
|
||||
# Update the session with the logs URL
|
||||
await supabase.table("sessions").update({"logs_url": public_url}).eq("id", session_id).execute()
|
||||
|
||||
logger.info(colored(f"Completed logs update for session: {session_id}", "yellow"))
|
||||
return JSONResponse({"status": "success", "logs_url": public_url})
|
||||
|
||||
except ExpiredJWTError:
|
||||
logger.warning("Expired JWT")
|
||||
return JSONResponse({"path": request.url.path, "message": "Expired Token"}, status_code=401)
|
||||
except RuntimeError as e:
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.error(f"{request.url.path}: Error updating logs: {e} Data received: {data}")
|
||||
except Exception as log_error:
|
||||
logger.error(f"{request.url.path}: Error updating logs: {e} Could not read data: {log_error}")
|
||||
|
||||
return JSONResponse(
|
||||
{
|
||||
"path": request.url.path,
|
||||
"message": f"Error updating logs: {e}",
|
||||
},
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/ttd/{ttd_id}")
|
||||
async def v2_get_ttd(ttd_id: str, request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
ttds_response = await supabase.table("ttd").select("*").eq("ttd_id", ttd_id).execute()
|
||||
return JSONResponse(ttds_response.data)
|
||||
except RuntimeError as e:
|
||||
logger.error(f"Error getting ttd: {e}")
|
||||
return JSONResponse(
|
||||
{"path": request.url.path, "message": f"Error getting ttd: {e}"},
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/developer_errors")
|
||||
async def v2_developer_errors(request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.debug(data)
|
||||
|
||||
developer_error = {
|
||||
"api_key": request.headers.get("X-Agentops-Api-Key"),
|
||||
"sdk_version": data.get("sdk_version", None),
|
||||
"type": data.get("type", None),
|
||||
"message": data.get("message", None),
|
||||
"stack_trace": data.get("stack_trace", None),
|
||||
"host_env": data.get("host_env", None),
|
||||
}
|
||||
|
||||
await supabase.table("developer_errors").insert(developer_error).execute()
|
||||
logger.info(
|
||||
colored(
|
||||
f"Completed request request for API Key: {request.headers.get('X-Agentops-Api-Key')}",
|
||||
"yellow",
|
||||
)
|
||||
)
|
||||
return JSONResponse("", status_code=204)
|
||||
except RuntimeError as e:
|
||||
try:
|
||||
data = await request.json()
|
||||
logger.error(f"{request.url.path}: Error posting developer_error: {e} Data received: {data}")
|
||||
except Exception as log_error:
|
||||
logger.error(
|
||||
f"{request.url.path}: Error posting developer_error: {e} Could not read data: {log_error}"
|
||||
)
|
||||
|
||||
return JSONResponse(
|
||||
{
|
||||
"path": request.url.path,
|
||||
"message": f"Error posting developer_error: {e}",
|
||||
},
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/sessions/{session_id}/stats")
|
||||
async def v2_get_session_stats(session_id: str, request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
api_key = request.headers.get("X-Agentops-Api-Key")
|
||||
if api_key is None:
|
||||
raise RuntimeError("API Key is Missing")
|
||||
|
||||
validate_uuid(api_key)
|
||||
|
||||
# Get project ID from API key
|
||||
project_response = await supabase.table("projects").select("id").eq("api_key", api_key).execute()
|
||||
project = project_response.data[0] if project_response.data else None
|
||||
|
||||
if not project:
|
||||
raise RuntimeError("Invalid API Key")
|
||||
|
||||
# Check if session belongs to this project
|
||||
session_response = (
|
||||
await supabase.table("sessions")
|
||||
.select("id")
|
||||
.eq("id", session_id)
|
||||
.eq("project_id", project["id"])
|
||||
.execute()
|
||||
)
|
||||
if not session_response.data:
|
||||
raise RuntimeError("Session does not belong to this project")
|
||||
|
||||
stats_response = await supabase.table("stats").select("*").eq("session_id", session_id).execute()
|
||||
stats = (
|
||||
stats_response.data[0]
|
||||
if stats_response.data
|
||||
else {
|
||||
"events": 0,
|
||||
"cost": "0.00",
|
||||
"prompt_tokens": 0,
|
||||
"completion_tokens": 0,
|
||||
"errors": 0,
|
||||
}
|
||||
)
|
||||
|
||||
return JSONResponse(stats)
|
||||
|
||||
except InvalidAPIKeyError as e:
|
||||
# This is a user error (invalid API key format), not a system error
|
||||
# Log as warning to avoid Sentry alerts
|
||||
logger.warning(f"{request.url.path}: Invalid API key format for session {session_id}")
|
||||
return JSONResponse({"path": request.url.path, "message": "Invalid API key format"}, status_code=400)
|
||||
except RuntimeError as e:
|
||||
logger.error(f"Error getting session stats: {e}")
|
||||
return JSONResponse({"path": request.url.path, "message": str(e)}, status_code=400)
|
||||
|
||||
|
||||
@router.get("/sessions/{session_id}/export")
|
||||
async def v2_export_session(session_id: str, request: Request, supabase: AsyncSupabaseClient):
|
||||
try:
|
||||
api_key = request.headers.get("X-Agentops-Api-Key")
|
||||
if api_key is None:
|
||||
raise RuntimeError("API Key is Missing")
|
||||
|
||||
validate_uuid(api_key)
|
||||
|
||||
# Get project ID from API key
|
||||
project_response = await supabase.table("projects").select("id").eq("api_key", api_key).execute()
|
||||
project = project_response.data[0] if project_response.data else None
|
||||
|
||||
if not project:
|
||||
raise RuntimeError("Invalid API Key")
|
||||
|
||||
# Check if session belongs to this project
|
||||
session_response = (
|
||||
await supabase.table("sessions")
|
||||
.select("id")
|
||||
.eq("id", session_id)
|
||||
.eq("project_id", project["id"])
|
||||
.execute()
|
||||
)
|
||||
if not session_response.data:
|
||||
raise RuntimeError("Session does not belong to this project")
|
||||
|
||||
session_response = await supabase.table("sessions").select("*").eq("id", session_id).execute()
|
||||
actions_response = await supabase.table("actions").select("*").eq("session_id", session_id).execute()
|
||||
llms_response = await supabase.table("llms").select("*").eq("session_id", session_id).execute()
|
||||
tools_response = await supabase.table("tools").select("*").eq("session_id", session_id).execute()
|
||||
errors_response = await supabase.table("errors").select("*").eq("session_id", session_id).execute()
|
||||
|
||||
export_data = {
|
||||
"session": session_response.data[0] if session_response.data else None,
|
||||
"actions": actions_response.data,
|
||||
"llms": llms_response.data,
|
||||
"tools": tools_response.data,
|
||||
"errors": errors_response.data,
|
||||
}
|
||||
|
||||
return JSONResponse(export_data)
|
||||
|
||||
except InvalidAPIKeyError as e:
|
||||
# This is a user error (invalid API key format), not a system error
|
||||
# Log as warning to avoid Sentry alerts
|
||||
logger.warning(f"{request.url.path}: Invalid API key format for session {session_id}")
|
||||
return JSONResponse({"path": request.url.path, "message": "Invalid API key format"}, status_code=400)
|
||||
except RuntimeError as e:
|
||||
logger.error(f"Error exporting session data: {e}")
|
||||
return JSONResponse({"path": request.url.path, "message": str(e)}, status_code=400)
|
||||
|
||||
|
||||
@router.get("/openapi.yaml")
|
||||
async def v2_openapi_yaml(request: Request):
|
||||
return JSONResponse(await request.send_file("openapi-spec-v2.yaml"))
|
||||
@@ -0,0 +1,123 @@
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
import pydantic
|
||||
|
||||
from fastapi import APIRouter, Depends, Request, HTTPException
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from agentops.common.orm import get_orm_session, Session
|
||||
from agentops.opsboard.models import ProjectModel
|
||||
from agentops.api.auth import JWTPayload, generate_jwt, get_jwt_token
|
||||
from agentops.api.exceptions import InvalidAPIKeyError
|
||||
from agentops.api.log_config import logger
|
||||
|
||||
"""
|
||||
Provides authentication functionality for obtaining JWT tokens.
|
||||
|
||||
This is used by the SDK to transform an API key into a JWT token so that it can
|
||||
rite data to the correct project.
|
||||
|
||||
Routes:
|
||||
- POST /v3/auth/token - Authenticate and issue JWT token
|
||||
- GET /v3/auth/token - Verify and return JWT token information
|
||||
"""
|
||||
|
||||
|
||||
router = APIRouter(prefix="/v3")
|
||||
|
||||
|
||||
class TokenSchema(pydantic.BaseModel):
|
||||
api_key: str
|
||||
|
||||
|
||||
class TokenResponse(pydantic.BaseModel):
|
||||
token: str
|
||||
project_id: str
|
||||
project_prem_status: str
|
||||
|
||||
@pydantic.field_validator("project_id", "token", mode="before")
|
||||
@classmethod
|
||||
def format_uuid(cls, v):
|
||||
"""Convert UUID to string format."""
|
||||
if isinstance(v, str):
|
||||
return v
|
||||
return str(v)
|
||||
|
||||
|
||||
class VerifyTokenResponse(pydantic.BaseModel):
|
||||
message: str
|
||||
payload: dict
|
||||
expires_at: str
|
||||
|
||||
@pydantic.field_validator("expires_at", mode="before")
|
||||
@classmethod
|
||||
def format_datetime(cls, v):
|
||||
"""Convert a timestamp to ISO str format."""
|
||||
return datetime.fromtimestamp(v).isoformat()
|
||||
|
||||
@pydantic.field_validator("payload", mode="before")
|
||||
@classmethod
|
||||
def format_payload(cls, v):
|
||||
"""Convert the payload to a dictionary format."""
|
||||
assert isinstance(v, JWTPayload)
|
||||
return v.asdict()
|
||||
|
||||
|
||||
@router.post("/auth/token")
|
||||
async def get_token(
|
||||
request: Request,
|
||||
body: TokenSchema,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> TokenResponse:
|
||||
"""Authenticate and issue JWT token"""
|
||||
try:
|
||||
api_key = UUID(body.api_key) # raises ValueError
|
||||
project = ProjectModel.get_by_api_key(orm, api_key)
|
||||
|
||||
if not project:
|
||||
raise InvalidAPIKeyError(403, "Invalid API key")
|
||||
|
||||
return TokenResponse(
|
||||
token=generate_jwt(project),
|
||||
project_id=project.id,
|
||||
project_prem_status=project.org.prem_status.value,
|
||||
)
|
||||
|
||||
except ValueError as e:
|
||||
# api_key is not a valid UUID
|
||||
logger.warning(f"Invalid API key format: {str(e)}")
|
||||
return JSONResponse({"error": "Invalid API key format"}, status_code=400)
|
||||
except InvalidAPIKeyError as e:
|
||||
# project not found for the given api_key
|
||||
logger.warning(f"Invalid API key: {str(e)}")
|
||||
return JSONResponse({"error": str(e)}, status_code=e.code)
|
||||
except Exception as e:
|
||||
logger.error(f"Error authenticating: {str(e)}")
|
||||
return JSONResponse({"error": "Authentication failed"}, status_code=500)
|
||||
|
||||
|
||||
@router.get("/auth/token")
|
||||
async def verify_token(
|
||||
request: Request,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
jwt_payload: JWTPayload = Depends(get_jwt_token),
|
||||
) -> VerifyTokenResponse:
|
||||
"""
|
||||
Verify and return JWT token information
|
||||
|
||||
This endpoint verifies the JWT token in the Authorization header
|
||||
and returns the token payload if valid.
|
||||
"""
|
||||
project: ProjectModel = ProjectModel.get_by_id(orm, jwt_payload.project_id)
|
||||
|
||||
# if a user has upgraded or downgraded their plan, we need to reauthorize
|
||||
# the token to use the new plan. the SDK will call acquire a new auth token
|
||||
# when it sees a 401 response code.
|
||||
if project.org.prem_status.value != jwt_payload.project_prem_status:
|
||||
raise HTTPException(status_code=401, detail="Reauthorized to use new plan")
|
||||
|
||||
return VerifyTokenResponse(
|
||||
message="JWT token is valid",
|
||||
payload=jwt_payload,
|
||||
expires_at=jwt_payload.exp,
|
||||
)
|
||||
@@ -0,0 +1,66 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from agentops.common.route_config import RouteConfig, register_routes
|
||||
from agentops.auth.middleware import AuthenticatedRoute
|
||||
|
||||
from .metrics.views import ProjectMetricsView
|
||||
from .traces.views import TraceListView, TraceDetailView
|
||||
from .logs import LogsUploadView, get_trace_logs
|
||||
from .objects import ObjectUploadView
|
||||
|
||||
from agentops.api.routes.v4.stripe_webhooks import router as stripe_webhooks_router
|
||||
|
||||
__all__ = ["router"]
|
||||
|
||||
|
||||
router = APIRouter(prefix="/v4")
|
||||
|
||||
|
||||
route_config: list[RouteConfig] = [
|
||||
# Metrics
|
||||
RouteConfig(
|
||||
name='get_project_metrics',
|
||||
path="/meterics/project/{project_id}",
|
||||
endpoint=ProjectMetricsView,
|
||||
methods=["GET"],
|
||||
),
|
||||
# Traces
|
||||
RouteConfig(
|
||||
name='get_project_traces',
|
||||
path="/traces/list/{project_id}",
|
||||
endpoint=TraceListView,
|
||||
methods=["GET"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='get_trace',
|
||||
path="/traces/detail/{trace_id}",
|
||||
endpoint=TraceDetailView,
|
||||
methods=["GET"],
|
||||
),
|
||||
# Objects
|
||||
RouteConfig(
|
||||
name='upload_object',
|
||||
path="/objects/upload/",
|
||||
endpoint=ObjectUploadView,
|
||||
methods=["POST"],
|
||||
),
|
||||
# Logs
|
||||
RouteConfig(
|
||||
name='upload_logs',
|
||||
path="/logs/upload/",
|
||||
endpoint=LogsUploadView,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='get_trace_logs',
|
||||
path="/logs/{trace_id}",
|
||||
endpoint=get_trace_logs,
|
||||
methods=["GET"],
|
||||
),
|
||||
]
|
||||
|
||||
api_router = APIRouter(route_class=AuthenticatedRoute)
|
||||
register_routes(api_router, route_config, prefix="/v4")
|
||||
router.include_router(api_router)
|
||||
|
||||
router.include_router(stripe_webhooks_router)
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Custom Exceptions for the v4 endpoints"""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class InvalidParameterError(Exception):
|
||||
"""Exception raised for invalid parameter values."""
|
||||
|
||||
def __init__(self, param_name: str, message: str):
|
||||
self.param_name = param_name
|
||||
self.message = message
|
||||
super().__init__(f"Invalid parameter '{param_name}': {message}")
|
||||
|
||||
|
||||
class DatabaseError(Exception):
|
||||
"""Exception raised for database-related errors."""
|
||||
|
||||
def __init__(self, message: str, query: Optional[str] = None):
|
||||
self.message = message
|
||||
self.query = query
|
||||
super().__init__(f"Database error: {message}")
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
API for receiving log files from the AgentOps SDK.
|
||||
|
||||
Authorized by JWT.
|
||||
Accept a body of content to store.
|
||||
Returns the public URL where the data can be accessed.
|
||||
|
||||
Uses Supabase Bucket storage (via the AWS S3 interface).
|
||||
"""
|
||||
|
||||
import re
|
||||
from fastapi import Depends, HTTPException, Request, status
|
||||
|
||||
from agentops.common.environment import APP_URL, FREEPLAN_LOGS_LINE_LIMIT
|
||||
from agentops.common.views import add_cors_headers
|
||||
from agentops.common.orm import Session, get_orm_session
|
||||
from agentops.common.freeplan import FreePlanFilteredResponse
|
||||
from agentops.auth.views import public_route
|
||||
from agentops.opsboard.models import ProjectModel
|
||||
from agentops.api.environment import SUPABASE_S3_LOGS_BUCKET
|
||||
from agentops.api.storage import get_s3_client
|
||||
from agentops.api.storage import BaseObjectUploadView
|
||||
from agentops.api.models.traces import TraceModel
|
||||
|
||||
|
||||
@public_route
|
||||
class LogsUploadView(BaseObjectUploadView):
|
||||
bucket_name: str = SUPABASE_S3_LOGS_BUCKET
|
||||
|
||||
@property
|
||||
def filename(self) -> str:
|
||||
"""Generate a unique filename for the object"""
|
||||
trace_id = self.request.headers.get("Trace-Id")
|
||||
|
||||
if not trace_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="No trace ID provided",
|
||||
)
|
||||
|
||||
# only allow alphanumeric characters, underscores, dashes, and dots
|
||||
if re.search(r"[^a-zA-Z0-9_.-]", trace_id):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Trace ID contains invalid characters",
|
||||
)
|
||||
|
||||
return f'{trace_id}.log'
|
||||
|
||||
|
||||
class LogContentResponse(FreePlanFilteredResponse):
|
||||
_freeplan_maxlines = {
|
||||
"content": FREEPLAN_LOGS_LINE_LIMIT,
|
||||
}
|
||||
|
||||
content: str
|
||||
trace_id: str
|
||||
|
||||
|
||||
def convert_trace_id(trace_id: str) -> str:
|
||||
"""Convert hex trace_id to int if in hex format (contains at least one letter a-f)."""
|
||||
try:
|
||||
# Only convert if string contains hex letters and is valid hex
|
||||
if any(c in 'abcdefABCDEF' for c in trace_id) and all(
|
||||
c in '0123456789abcdefABCDEF' for c in trace_id
|
||||
):
|
||||
return str(int(trace_id, 16))
|
||||
return trace_id
|
||||
except ValueError:
|
||||
return trace_id
|
||||
|
||||
|
||||
@add_cors_headers(
|
||||
origins=[APP_URL],
|
||||
methods=["GET", "OPTIONS"],
|
||||
)
|
||||
async def get_trace_logs(
|
||||
*,
|
||||
request: Request,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
trace_id: str,
|
||||
) -> LogContentResponse:
|
||||
"""
|
||||
Retrieve logs for a specific trace ID.
|
||||
Verifies that the user has access to the trace before returning the logs.
|
||||
"""
|
||||
trace_id_int = convert_trace_id(trace_id)
|
||||
|
||||
trace = await TraceModel.select(
|
||||
filters={
|
||||
"trace_id": trace_id,
|
||||
}
|
||||
)
|
||||
if not trace.spans: # trace does not exist
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You do not have access to this trace",
|
||||
)
|
||||
|
||||
project = ProjectModel.get_by_id(orm, trace.project_id)
|
||||
if not project or not project.org.is_user_member(request.state.session.user_id):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You do not have access to this trace",
|
||||
)
|
||||
|
||||
try:
|
||||
s3_client = get_s3_client()
|
||||
response = s3_client.get_object(
|
||||
Bucket=SUPABASE_S3_LOGS_BUCKET,
|
||||
Key=f"{trace_id_int}.log",
|
||||
)
|
||||
content = response['Body'].read().decode('utf-8')
|
||||
|
||||
return LogContentResponse(
|
||||
content=content,
|
||||
trace_id=trace_id,
|
||||
freeplan_truncated=project.is_freeplan,
|
||||
)
|
||||
|
||||
except s3_client.exceptions.NoSuchKey:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"No logs found for trace ID: {trace_id}",
|
||||
)
|
||||
@@ -0,0 +1,95 @@
|
||||
from typing import Optional, Any
|
||||
from decimal import Decimal
|
||||
from datetime import datetime, date
|
||||
from uuid import UUID
|
||||
import pydantic
|
||||
|
||||
|
||||
class SpanCount(pydantic.BaseModel):
|
||||
total: int
|
||||
success: int
|
||||
fail: int
|
||||
unknown: int
|
||||
indeterminate: int
|
||||
|
||||
|
||||
class TotalTokens(pydantic.BaseModel):
|
||||
all: int
|
||||
success: int
|
||||
fail: int
|
||||
|
||||
|
||||
class AverageTokens(pydantic.BaseModel):
|
||||
all: float
|
||||
success: float
|
||||
fail: float
|
||||
|
||||
@pydantic.field_validator('all', 'success', 'fail', mode='before')
|
||||
@classmethod
|
||||
def round_float(cls, v: float) -> float:
|
||||
"""Round all values to 2 decimal places."""
|
||||
return round(v, 2)
|
||||
|
||||
|
||||
class TokenMetrics(pydantic.BaseModel):
|
||||
total_cost: str
|
||||
average_cost_per_session: str
|
||||
prompt_tokens: int
|
||||
completion_tokens: int
|
||||
total_tokens: TotalTokens
|
||||
avg_tokens: AverageTokens
|
||||
|
||||
@pydantic.field_validator('total_cost', 'average_cost_per_session', mode='before')
|
||||
@classmethod
|
||||
def format_cost(cls, v: Decimal) -> str:
|
||||
"""Ensure the cost is formatted as a string with 5 decimal places."""
|
||||
return f"{float(v):.5f}"
|
||||
|
||||
|
||||
class DurationMetrics(pydantic.BaseModel):
|
||||
min_duration_ns: Optional[int] = None
|
||||
max_duration_ns: Optional[int] = None
|
||||
avg_duration_ns: int
|
||||
total_duration_ns: Optional[int] = None
|
||||
trace_durations: list[Any]
|
||||
|
||||
|
||||
class ProjectMetricsResponse(pydantic.BaseModel):
|
||||
project_id: str
|
||||
trace_count: int
|
||||
span_count: SpanCount
|
||||
token_metrics: TokenMetrics
|
||||
duration_metrics: DurationMetrics
|
||||
success_datetime: list[str]
|
||||
fail_datetime: list[str]
|
||||
indeterminate_datetime: list[str]
|
||||
spans_per_trace: dict[int, int]
|
||||
trace_durations: list[int]
|
||||
trace_cost_dates: dict[str, float]
|
||||
start_time: str
|
||||
end_time: str
|
||||
freeplan_truncated: bool = False
|
||||
|
||||
@pydantic.field_validator('project_id', mode='before')
|
||||
@classmethod
|
||||
def format_uuid(cls, v: UUID) -> str:
|
||||
"""Ensure the project_id is formatted as a string."""
|
||||
return str(v)
|
||||
|
||||
@pydantic.field_validator('trace_cost_dates', mode='before')
|
||||
@classmethod
|
||||
def format_date_keys_float_values(cls, v: dict[date, Decimal]) -> dict[str, float]:
|
||||
"""Ensure the trace_cost_dates are able to be serialized properly."""
|
||||
return {date.isoformat(): float(cost) for date, cost in v.items()}
|
||||
|
||||
@pydantic.field_validator('success_datetime', 'fail_datetime', 'indeterminate_datetime', mode='before')
|
||||
@classmethod
|
||||
def format_datetime_list(cls, v: list[datetime]) -> list[str]:
|
||||
"""Ensure the datetime lists are formatted as ISO strings."""
|
||||
return [d.isoformat() for d in v]
|
||||
|
||||
@pydantic.field_validator('start_time', 'end_time', mode='before')
|
||||
@classmethod
|
||||
def format_datetime(cls, v: datetime) -> str:
|
||||
"""Ensure the start_time and end_time are formatted as ISO strings."""
|
||||
return v.isoformat()
|
||||
@@ -0,0 +1,217 @@
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
from fastapi import Depends, Query, HTTPException
|
||||
import hashlib
|
||||
|
||||
from agentops.common.environment import APP_URL, FREEPLAN_METRICS_DAYS_CUTOFF
|
||||
from agentops.common.route_config import BaseView
|
||||
from agentops.common.views import add_cors_headers
|
||||
from agentops.common.orm import get_orm_session, Session
|
||||
from agentops.common.freeplan import freeplan_clamp_start_time, freeplan_clamp_end_time
|
||||
|
||||
from agentops.opsboard.models import ProjectModel
|
||||
from agentops.api.models.metrics import ProjectMetricsModel
|
||||
|
||||
from .responses import (
|
||||
ProjectMetricsResponse,
|
||||
SpanCount,
|
||||
TotalTokens,
|
||||
AverageTokens,
|
||||
TokenMetrics,
|
||||
DurationMetrics,
|
||||
)
|
||||
|
||||
|
||||
# Simple in-memory cache with TTL
|
||||
from time import time
|
||||
|
||||
|
||||
class MetricsCache:
|
||||
def __init__(self, ttl_seconds: int = 300): # 5 minute default TTL
|
||||
self._cache = {}
|
||||
self._ttl = ttl_seconds
|
||||
|
||||
def _make_key(self, project_id: str, start_time: Optional[datetime], end_time: Optional[datetime]) -> str:
|
||||
"""Create a cache key from parameters"""
|
||||
key_parts = [
|
||||
project_id,
|
||||
start_time.isoformat() if start_time else "none",
|
||||
end_time.isoformat() if end_time else "none",
|
||||
]
|
||||
key_str = "|".join(key_parts)
|
||||
return hashlib.md5(key_str.encode()).hexdigest()
|
||||
|
||||
def get(self, project_id: str, start_time: Optional[datetime], end_time: Optional[datetime]):
|
||||
"""Get cached value if not expired"""
|
||||
key = self._make_key(project_id, start_time, end_time)
|
||||
if key in self._cache:
|
||||
cached_data, cached_time = self._cache[key]
|
||||
if time() - cached_time < self._ttl:
|
||||
return cached_data
|
||||
else:
|
||||
# Expired, remove from cache
|
||||
del self._cache[key]
|
||||
return None
|
||||
|
||||
def set(self, project_id: str, start_time: Optional[datetime], end_time: Optional[datetime], data):
|
||||
"""Set cache value with current timestamp"""
|
||||
key = self._make_key(project_id, start_time, end_time)
|
||||
self._cache[key] = (data, time())
|
||||
|
||||
# Simple cleanup - remove old entries if cache gets too large
|
||||
if len(self._cache) > 1000:
|
||||
# Remove oldest 100 entries
|
||||
sorted_items = sorted(self._cache.items(), key=lambda x: x[1][1])
|
||||
for key, _ in sorted_items[:100]:
|
||||
del self._cache[key]
|
||||
|
||||
|
||||
# Global cache instance
|
||||
metrics_cache = MetricsCache(ttl_seconds=300) # 5 minute cache
|
||||
|
||||
|
||||
class ProjectMetricsView(BaseView):
|
||||
"""
|
||||
View class for handling the project metrics endpoint. This class encapsulates
|
||||
the logic for retrieving and formatting project metrics data.
|
||||
"""
|
||||
|
||||
orm: Session
|
||||
project: ProjectModel
|
||||
freeplan_truncated: bool = False
|
||||
|
||||
@add_cors_headers(
|
||||
origins=[APP_URL],
|
||||
methods=["GET", "OPTIONS"],
|
||||
)
|
||||
async def __call__(
|
||||
self,
|
||||
*,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
project_id: str,
|
||||
start_time: Optional[datetime] = Query(
|
||||
None,
|
||||
description="Filter by start time (ISO 8601 format, e.g., '2023-01-01T00:00:00Z')",
|
||||
),
|
||||
end_time: Optional[datetime] = Query(
|
||||
None,
|
||||
description="Filter by end time (ISO 8601 format, e.g., '2023-01-01T00:00:00Z')",
|
||||
),
|
||||
) -> ProjectMetricsResponse:
|
||||
"""
|
||||
Callable method to handle the request and return a JSONResponse. This method
|
||||
validates the input parameters, retrieves the metrics data, formats the
|
||||
response and converts exceptions to responses.
|
||||
"""
|
||||
self.orm = orm
|
||||
self.project = await self.get_project(project_id)
|
||||
|
||||
# Normalize time parameters for caching
|
||||
normalized_start = self.get_start_time(start_time)
|
||||
normalized_end = self.get_end_time(end_time)
|
||||
|
||||
# Check cache first
|
||||
cached_response = metrics_cache.get(project_id, normalized_start, normalized_end)
|
||||
if cached_response is not None:
|
||||
# Return cached response with freeplan_truncated flag
|
||||
cached_response.freeplan_truncated = self.freeplan_truncated
|
||||
return cached_response
|
||||
|
||||
metrics = await ProjectMetricsModel.select(
|
||||
filters={
|
||||
'project_id': self.project.id,
|
||||
'start_time': normalized_start,
|
||||
'end_time': normalized_end,
|
||||
}
|
||||
)
|
||||
|
||||
# TODO handle empty response
|
||||
response = await self.get_response(metrics)
|
||||
|
||||
# Cache the response
|
||||
metrics_cache.set(project_id, normalized_start, normalized_end, response)
|
||||
|
||||
return response
|
||||
|
||||
def get_start_time(self, start_time: Optional[datetime]) -> Optional[datetime]:
|
||||
"""Validates and formats the start_time parameter with freeplan handling."""
|
||||
if self.project.is_freeplan:
|
||||
start_time, modified = freeplan_clamp_start_time(start_time, FREEPLAN_METRICS_DAYS_CUTOFF)
|
||||
self.freeplan_truncated |= modified
|
||||
|
||||
return start_time
|
||||
|
||||
def get_end_time(self, end_time: Optional[datetime]) -> Optional[datetime]:
|
||||
"""Validates and formats the end_time parameter with freeplan handling."""
|
||||
if self.project.is_freeplan:
|
||||
end_time, modified = freeplan_clamp_end_time(end_time, FREEPLAN_METRICS_DAYS_CUTOFF)
|
||||
self.freeplan_truncated |= modified
|
||||
|
||||
return end_time
|
||||
|
||||
async def get_project(self, project_id: str | UUID) -> ProjectModel:
|
||||
project = ProjectModel.get_by_id(self.orm, project_id)
|
||||
|
||||
if not project or not project.org.is_user_member(self.request.state.session.user_id):
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
return project
|
||||
|
||||
async def get_response(self, metrics: ProjectMetricsModel) -> ProjectMetricsResponse:
|
||||
"""
|
||||
Loads an aggregated collection of trace metrics data for a given project.
|
||||
|
||||
`ProjectMetricsModel` handles retrieving and aggregating the data from the
|
||||
databases, as well as performing calculations and normalizing the data
|
||||
(normalizing meaning it will always return the expected types).
|
||||
|
||||
The response types format the data in a suitable format for the frontend
|
||||
and handle all serialization.
|
||||
"""
|
||||
|
||||
return ProjectMetricsResponse(
|
||||
project_id=self.project.id,
|
||||
trace_count=metrics.duration.trace_count,
|
||||
start_time=metrics.duration.start_time,
|
||||
end_time=metrics.duration.end_time,
|
||||
span_count=SpanCount(
|
||||
total=metrics.span_count,
|
||||
success=metrics.success_count,
|
||||
fail=metrics.fail_count,
|
||||
unknown=metrics.indeterminate_count,
|
||||
indeterminate=metrics.indeterminate_count,
|
||||
),
|
||||
token_metrics=TokenMetrics(
|
||||
total_cost=metrics.total_cost,
|
||||
average_cost_per_session=metrics.average_cost_per_trace,
|
||||
prompt_tokens=metrics.prompt_tokens,
|
||||
completion_tokens=metrics.completion_tokens,
|
||||
cache_read_input_tokens=metrics.cache_read_input_tokens,
|
||||
reasoning_tokens=metrics.reasoning_tokens,
|
||||
total_tokens=TotalTokens(
|
||||
all=metrics.total_tokens,
|
||||
success=metrics.success_tokens,
|
||||
fail=metrics.fail_tokens,
|
||||
),
|
||||
avg_tokens=AverageTokens(
|
||||
all=metrics.avg_tokens,
|
||||
success=metrics.avg_success_tokens,
|
||||
fail=metrics.avg_fail_tokens,
|
||||
),
|
||||
),
|
||||
duration_metrics=DurationMetrics(
|
||||
min_duration_ns=metrics.duration.min_duration,
|
||||
max_duration_ns=metrics.duration.max_duration,
|
||||
avg_duration_ns=metrics.duration.avg_duration,
|
||||
total_duration_ns=metrics.duration.total_duration,
|
||||
trace_durations=[td.trace_duration for td in metrics.trace_durations],
|
||||
),
|
||||
success_datetime=metrics.success_dates,
|
||||
fail_datetime=metrics.fail_dates,
|
||||
indeterminate_datetime=metrics.indeterminate_dates,
|
||||
trace_durations=[td.trace_duration for td in metrics.trace_durations],
|
||||
spans_per_trace=metrics.spans_per_trace,
|
||||
trace_cost_dates=metrics.trace_cost_dates,
|
||||
freeplan_truncated=self.freeplan_truncated,
|
||||
)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""
|
||||
API for storing object data.
|
||||
|
||||
Authorized by JWT.
|
||||
Accept a body of content to store.
|
||||
Returns the public URL where the data can be accessed.
|
||||
|
||||
Uses Supabase Bucket storage (via the AWS S3 interface).
|
||||
"""
|
||||
|
||||
import uuid
|
||||
|
||||
from agentops.api.environment import SUPABASE_S3_BUCKET
|
||||
from agentops.api.storage import BaseObjectUploadView
|
||||
from agentops.auth.views import public_route
|
||||
|
||||
|
||||
@public_route
|
||||
class ObjectUploadView(BaseObjectUploadView):
|
||||
bucket_name: str = SUPABASE_S3_BUCKET
|
||||
|
||||
@property
|
||||
def filename(self) -> str:
|
||||
"""Generate a unique filename for the object"""
|
||||
if not hasattr(self, '_filename'):
|
||||
self._filename = f"{self.token['project_id']}/{uuid.uuid4().hex}"
|
||||
return self._filename
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,140 @@
|
||||
from typing import Optional, Any
|
||||
from datetime import datetime
|
||||
import pydantic
|
||||
|
||||
from agentops.common.otel import otel_attributes_to_nested
|
||||
from agentops.common.freeplan import FreePlanFilteredResponse
|
||||
from agentops.api.models.span_metrics import (
|
||||
SpanMetricsResponse,
|
||||
TraceMetricsResponse,
|
||||
)
|
||||
|
||||
|
||||
class TraceListItem(pydantic.BaseModel):
|
||||
freeplan_truncated: bool = False
|
||||
trace_id: str
|
||||
root_service_name: str
|
||||
root_span_name: str
|
||||
start_time: str
|
||||
end_time: str
|
||||
duration: int
|
||||
span_count: int
|
||||
error_count: int
|
||||
tags: Optional[list[str]] = None
|
||||
total_cost: Optional[float] = None
|
||||
|
||||
@pydantic.field_validator('start_time', 'end_time', mode='before')
|
||||
def format_datetime(cls, v: datetime) -> str:
|
||||
"""Ensure the start_time and end_time are formatted as ISO strings."""
|
||||
return v.isoformat()
|
||||
|
||||
|
||||
class TraceListResponse(pydantic.BaseModel):
|
||||
traces: list[TraceListItem]
|
||||
metrics: TraceMetricsResponse
|
||||
total: int
|
||||
limit: int
|
||||
offset: int
|
||||
freeplan_truncated: bool = False
|
||||
|
||||
|
||||
class SpanItem(FreePlanFilteredResponse):
|
||||
_freeplan_exclude = (
|
||||
'attributes',
|
||||
'resource_attributes',
|
||||
'span_attributes',
|
||||
'event_timestamps',
|
||||
'event_names',
|
||||
'event_attributes',
|
||||
'link_trace_ids',
|
||||
'link_span_ids',
|
||||
'link_trace_states',
|
||||
'link_attributes',
|
||||
# 'metrics',
|
||||
)
|
||||
|
||||
span_id: str
|
||||
parent_span_id: Optional[str] = None
|
||||
|
||||
span_name: str
|
||||
span_kind: str
|
||||
span_type: Optional[str] = None # populated post-init
|
||||
service_name: str
|
||||
|
||||
start_time: str
|
||||
end_time: str
|
||||
duration: int
|
||||
status_code: str
|
||||
status_message: Optional[str] = None
|
||||
|
||||
attributes: dict[str, Any] = pydantic.Field(default_factory=dict)
|
||||
resource_attributes: dict[str, Any] = pydantic.Field(default_factory=dict)
|
||||
span_attributes: dict[str, Any] = pydantic.Field(default_factory=dict)
|
||||
|
||||
event_timestamps: list[str] = pydantic.Field(default_factory=list)
|
||||
event_names: list[str] = pydantic.Field(default_factory=list)
|
||||
event_attributes: list[Any] = pydantic.Field(default_factory=list)
|
||||
|
||||
link_trace_ids: list[str] = pydantic.Field(default_factory=list)
|
||||
link_span_ids: list[str] = pydantic.Field(default_factory=list)
|
||||
link_trace_states: list[str] = pydantic.Field(default_factory=list)
|
||||
link_attributes: list[Any] = pydantic.Field(default_factory=list)
|
||||
|
||||
metrics: Optional[SpanMetricsResponse] = None
|
||||
|
||||
@pydantic.field_validator('start_time', 'end_time', mode='before')
|
||||
def format_datetime(cls, v: datetime) -> str:
|
||||
"""Ensure the start_time and end_time are formatted as ISO strings."""
|
||||
return v.isoformat()
|
||||
|
||||
@pydantic.field_validator('event_timestamps', mode='before')
|
||||
def format_event_timestamps(cls, v: list[datetime]) -> list[str]:
|
||||
"""Ensure event timestamps are formatted as ISO strings."""
|
||||
return [dt.isoformat() for dt in v]
|
||||
|
||||
@pydantic.model_validator(mode='after')
|
||||
def set_span_type(self):
|
||||
if self.span_attributes:
|
||||
self.span_type = self.format_span_type(self.span_attributes)
|
||||
|
||||
return self
|
||||
|
||||
def format_span_type(self, data: Any, current_path: str = "") -> str:
|
||||
"""Determine the span type from the span attributes dictionary."""
|
||||
# TODO this is LLM slop migrated from the v4 release and needs to be refactored
|
||||
SPAN_TYPE_MAP = {
|
||||
"gen_ai": "request",
|
||||
"agent": "agent",
|
||||
"tool": "tool",
|
||||
}
|
||||
if isinstance(data, dict):
|
||||
# Check if current path/key is in SPAN_TYPE_MAP
|
||||
for key in data.keys():
|
||||
full_path = f"{current_path}.{key}" if current_path else key
|
||||
if key in SPAN_TYPE_MAP:
|
||||
return SPAN_TYPE_MAP[key]
|
||||
|
||||
# Recursively check nested dictionaries
|
||||
result = self.format_span_type(data[key], full_path)
|
||||
if result != "other":
|
||||
return result
|
||||
elif isinstance(data, list):
|
||||
# Check each item in the list
|
||||
for item in data:
|
||||
result = self.format_span_type(item, current_path)
|
||||
if result != "other":
|
||||
return result
|
||||
|
||||
return "other"
|
||||
|
||||
@pydantic.field_validator('attributes', 'resource_attributes', 'span_attributes', mode='before')
|
||||
def format_attributes(cls, v: dict[str, str]) -> dict[str, Any]:
|
||||
return otel_attributes_to_nested(v)
|
||||
|
||||
|
||||
class TraceDetailResponse(FreePlanFilteredResponse):
|
||||
project_id: str
|
||||
trace_id: str
|
||||
tags: Optional[list[str]] = pydantic.Field(default_factory=list)
|
||||
metrics: TraceMetricsResponse
|
||||
spans: list[SpanItem]
|
||||
@@ -0,0 +1,397 @@
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
from fastapi import Depends, Query, HTTPException, status
|
||||
import hashlib
|
||||
from time import time
|
||||
|
||||
from agentops.common.environment import (
|
||||
APP_URL,
|
||||
FREEPLAN_TRACE_MIN_NUM,
|
||||
FREEPLAN_TRACE_DAYS_CUTOFF,
|
||||
FREEPLAN_SPANS_LIST_LIMIT,
|
||||
)
|
||||
from agentops.common.route_config import BaseView
|
||||
from agentops.common.views import add_cors_headers
|
||||
from agentops.common.orm import get_orm_session, Session
|
||||
from agentops.common.freeplan import freeplan_clamp_datetime
|
||||
|
||||
from agentops.opsboard.models import ProjectModel
|
||||
from agentops.api.models.traces import TraceModel, TraceSummaryModel, TraceListModel
|
||||
from agentops.api.models.span_metrics import SpanMetricsResponse, TraceMetricsResponse
|
||||
|
||||
from .responses import (
|
||||
TraceListResponse,
|
||||
TraceListItem,
|
||||
TraceDetailResponse,
|
||||
SpanItem,
|
||||
)
|
||||
|
||||
|
||||
def has_llm_attributes(span_attributes: dict) -> bool:
|
||||
"""
|
||||
Check if a span has LLM-related attributes that indicate it should have metrics.
|
||||
Based on the OpenTelemetry semantic conventions for AI and LLM spans.
|
||||
"""
|
||||
# Check for Gen AI attributes
|
||||
gen_ai_attrs = [
|
||||
'gen_ai.completion',
|
||||
'gen_ai.prompt',
|
||||
'gen_ai.usage',
|
||||
'gen_ai.usage.prompt_tokens',
|
||||
'gen_ai.usage.completion_tokens',
|
||||
'gen_ai.usage.total_tokens',
|
||||
'gen_ai.usage.prompt_cost',
|
||||
'gen_ai.usage.completion_cost',
|
||||
'gen_ai.usage.total_cost',
|
||||
'gen_ai.usage.cache_read_input_tokens',
|
||||
'gen_ai.usage.reasoning_tokens',
|
||||
]
|
||||
|
||||
# Check for legacy LLM attributes
|
||||
legacy_attrs = [
|
||||
'ai.system',
|
||||
'ai.llm',
|
||||
'llm.request.model',
|
||||
'llm.response.model',
|
||||
'llm.system',
|
||||
]
|
||||
|
||||
# Check if any of these attributes exist in the span
|
||||
for attr in gen_ai_attrs + legacy_attrs:
|
||||
if attr in span_attributes:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
# Simple in-memory cache for trace lists
|
||||
class TraceListCache:
|
||||
def __init__(self, ttl_seconds: int = 300): # 5 minute default TTL
|
||||
self._cache = {}
|
||||
self._ttl = ttl_seconds
|
||||
|
||||
def _make_key(
|
||||
self,
|
||||
project_id: str,
|
||||
start_time: Optional[datetime],
|
||||
end_time: Optional[datetime],
|
||||
query: Optional[str],
|
||||
limit: int,
|
||||
offset: int,
|
||||
order_by: str,
|
||||
sort_order: str,
|
||||
) -> str:
|
||||
"""Create a cache key from parameters"""
|
||||
key_parts = [
|
||||
project_id,
|
||||
start_time.isoformat() if start_time else "none",
|
||||
end_time.isoformat() if end_time else "none",
|
||||
query or "none",
|
||||
str(limit),
|
||||
str(offset),
|
||||
order_by,
|
||||
sort_order,
|
||||
]
|
||||
key_str = "|".join(key_parts)
|
||||
return hashlib.md5(key_str.encode()).hexdigest()
|
||||
|
||||
def get(self, **kwargs):
|
||||
"""Get cached value if not expired"""
|
||||
key = self._make_key(**kwargs)
|
||||
if key in self._cache:
|
||||
cached_data, cached_time = self._cache[key]
|
||||
if time() - cached_time < self._ttl:
|
||||
return cached_data
|
||||
else:
|
||||
del self._cache[key]
|
||||
return None
|
||||
|
||||
def set(self, data, **kwargs):
|
||||
"""Set cache value with current timestamp"""
|
||||
key = self._make_key(**kwargs)
|
||||
self._cache[key] = (data, time())
|
||||
|
||||
# Simple cleanup
|
||||
if len(self._cache) > 500:
|
||||
sorted_items = sorted(self._cache.items(), key=lambda x: x[1][1])
|
||||
for key, _ in sorted_items[:50]:
|
||||
del self._cache[key]
|
||||
|
||||
|
||||
# Global cache instance
|
||||
# Reduce cache TTL to 30 seconds to ensure newly ingested traces appear promptly
|
||||
trace_list_cache = TraceListCache(ttl_seconds=30) # 30-second cache for trace lists
|
||||
|
||||
|
||||
class BaseTraceView(BaseView):
|
||||
"""
|
||||
Common base class for trace views.
|
||||
"""
|
||||
|
||||
orm: Session
|
||||
project: ProjectModel
|
||||
freeplan_truncated: bool = False
|
||||
|
||||
async def get_project(self, project_id: str) -> ProjectModel:
|
||||
"""
|
||||
Retrieves the project by ID and checks if the user has access to it.
|
||||
Raises HTTPException if the project is not found or access is denied.
|
||||
"""
|
||||
project = ProjectModel.get_by_id(self.orm, project_id)
|
||||
|
||||
if not project or not project.org.is_user_member(self.request.state.session.user_id):
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Project not found")
|
||||
|
||||
return project
|
||||
|
||||
async def get_trace_ids(self, limit: int, offset: int = 0) -> set[str]:
|
||||
"""
|
||||
Retrieves the trace IDs for the project, limited by the specified number and offset.
|
||||
"""
|
||||
traces = await TraceSummaryModel.select(
|
||||
# fields=["trace_id"],
|
||||
filters={"project_id": self.project.id},
|
||||
order_by="start_time DESC",
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
)
|
||||
return {trace.trace_id for trace in traces}
|
||||
|
||||
async def trace_is_freeplan_truncated(self, trace: TraceModel) -> bool:
|
||||
"""
|
||||
Determines if a trace is truncated for free plan users.
|
||||
"""
|
||||
if not self.project.is_freeplan:
|
||||
return False # not a freeplan, always allow
|
||||
|
||||
if not hasattr(self, '_freeplan_trace_ids'): # cache the minimum visible trace IDs
|
||||
self._freeplan_trace_ids = await self.get_trace_ids(FREEPLAN_TRACE_MIN_NUM)
|
||||
|
||||
if trace.trace_id in self._freeplan_trace_ids: # trace is in the minimum visible traces, allow
|
||||
return False
|
||||
|
||||
return freeplan_clamp_datetime(trace.end_time, FREEPLAN_TRACE_DAYS_CUTOFF) > trace.end_time
|
||||
|
||||
|
||||
class TraceListView(BaseTraceView):
|
||||
"""
|
||||
TraceListView handles the logic for retrieving a list of traces based on the provided filters.
|
||||
It uses the TraceListModel to query the database and formats the response using the
|
||||
TraceListResponse model.
|
||||
"""
|
||||
|
||||
limit: int
|
||||
offset: int
|
||||
|
||||
@add_cors_headers(
|
||||
origins=[APP_URL],
|
||||
methods=["GET", "OPTIONS"],
|
||||
)
|
||||
async def __call__(
|
||||
self,
|
||||
*,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
project_id: str,
|
||||
start_time: Optional[datetime] = Query(
|
||||
None, description="Filter by timestamp start (ISO 8601 format, e.g., '2023-01-01T00:00:00Z')"
|
||||
),
|
||||
end_time: Optional[datetime] = Query(
|
||||
None, description="Filter by timestamp end (ISO 8601 format, e.g., '2023-01-01T00:00:00Z')"
|
||||
),
|
||||
query: Optional[str] = Query(
|
||||
None, description="Search by span name, trace_id, or tags (case insensitive)"
|
||||
),
|
||||
limit: int = Query(
|
||||
20, ge=1, le=100, description="Maximum number of traces to return (default: 20, max: 100)"
|
||||
),
|
||||
offset: int = Query(0, ge=0, description="Offset for pagination (default: 0)"),
|
||||
order_by: str = Query("start_time", description="Field to sort by (default: 'timestamp')."),
|
||||
sort_order: str = Query(
|
||||
# TODO restrict this to an Enum
|
||||
"DESC",
|
||||
description="Sort order for timestamp (ASC or DESC)",
|
||||
),
|
||||
) -> TraceListResponse:
|
||||
"""
|
||||
Callable method to handle the request and return a JSONResponse. This method
|
||||
validates the input parameters, retrieves the trace data, formats the
|
||||
response and converts exceptions to responses.
|
||||
"""
|
||||
self.orm = orm
|
||||
self.limit = limit
|
||||
self.offset = offset
|
||||
self.project = await self.get_project(project_id)
|
||||
|
||||
# Check cache first
|
||||
# Only use the cache if we're not requesting the very first page (offset == 0) OR
|
||||
# if specific filters are provided. The first page is the one that is most sensitive
|
||||
# to freshness because it shows the most recent traces. By fetching it live we ensure
|
||||
# the newest traces are always visible immediately after page refresh.
|
||||
should_use_cache = offset != 0 or query is not None or start_time is not None or end_time is not None
|
||||
|
||||
cache_params = {
|
||||
'project_id': project_id,
|
||||
'start_time': start_time,
|
||||
'end_time': end_time,
|
||||
'query': query,
|
||||
'limit': limit,
|
||||
'offset': offset,
|
||||
'order_by': order_by,
|
||||
'sort_order': sort_order,
|
||||
}
|
||||
|
||||
cached_response = None
|
||||
if should_use_cache:
|
||||
cached_response = trace_list_cache.get(**cache_params)
|
||||
|
||||
if cached_response is not None:
|
||||
# Update freeplan_truncated flag based on current project status
|
||||
if self.project.is_freeplan and cached_response.total > FREEPLAN_TRACE_MIN_NUM:
|
||||
return TraceListResponse(
|
||||
traces=cached_response.traces,
|
||||
metrics=cached_response.metrics,
|
||||
total=cached_response.total,
|
||||
limit=cached_response.limit,
|
||||
offset=cached_response.offset,
|
||||
freeplan_truncated=True,
|
||||
)
|
||||
return cached_response
|
||||
|
||||
trace_list = await TraceListModel.select(
|
||||
filters={
|
||||
"project_id": self.project.id,
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
},
|
||||
search=query,
|
||||
order_by=f"{order_by} {sort_order}",
|
||||
limit=self.limit,
|
||||
offset=self.offset,
|
||||
)
|
||||
|
||||
if self.project.is_freeplan and trace_list.trace_count > FREEPLAN_TRACE_MIN_NUM:
|
||||
# if we're showing more than the minimum number of traces we are truncating
|
||||
self.freeplan_truncated = True
|
||||
|
||||
response = await self.get_response(trace_list)
|
||||
|
||||
# Cache the response only if we used cache for this request
|
||||
if should_use_cache:
|
||||
trace_list_cache.set(response, **cache_params)
|
||||
|
||||
return response
|
||||
|
||||
async def get_response(self, trace_list: TraceListModel) -> TraceListResponse:
|
||||
"""
|
||||
Formats the trace list response from the TraceListModel instance.
|
||||
"""
|
||||
|
||||
return TraceListResponse(
|
||||
traces=[
|
||||
TraceListItem(
|
||||
trace_id=trace.trace_id,
|
||||
root_service_name=trace.service_name,
|
||||
root_span_name=trace.span_name,
|
||||
start_time=trace.start_time,
|
||||
end_time=trace.end_time,
|
||||
duration=trace.duration,
|
||||
span_count=trace.span_count,
|
||||
error_count=trace.error_count,
|
||||
tags=trace.tags,
|
||||
total_cost=trace.total_cost,
|
||||
freeplan_truncated=await self.trace_is_freeplan_truncated(trace),
|
||||
)
|
||||
for trace in trace_list.traces
|
||||
],
|
||||
metrics=TraceMetricsResponse.from_trace_with_metrics(trace_list),
|
||||
total=trace_list.trace_count,
|
||||
limit=self.limit,
|
||||
offset=self.offset,
|
||||
freeplan_truncated=self.freeplan_truncated,
|
||||
)
|
||||
|
||||
|
||||
class TraceDetailView(BaseTraceView):
|
||||
"""
|
||||
TraceDetailView handles the logic for retrieving the details of a specific
|
||||
trace based on the trace_id. It uses the TraceModel to query the database and
|
||||
formats the response using the TraceDetailResponse model.
|
||||
"""
|
||||
|
||||
@add_cors_headers(
|
||||
origins=[APP_URL],
|
||||
methods=["GET", "OPTIONS"],
|
||||
)
|
||||
async def __call__(
|
||||
self,
|
||||
*,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
trace_id: str,
|
||||
) -> TraceDetailResponse:
|
||||
"""
|
||||
Callable method to handle the request and return a JSONResponse. This method
|
||||
validates the input parameters, retrieves the trace data, formats the
|
||||
response and converts exceptions to responses.
|
||||
"""
|
||||
self.orm = orm
|
||||
|
||||
trace = await TraceModel.select(
|
||||
filters={
|
||||
"trace_id": trace_id,
|
||||
}
|
||||
)
|
||||
|
||||
if not trace.spans:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Trace not found.")
|
||||
|
||||
self.project = await self.get_project(trace.project_id)
|
||||
self.freeplan_truncated = await self.trace_is_freeplan_truncated(trace)
|
||||
|
||||
return await self.get_response(trace)
|
||||
|
||||
async def get_response(self, trace: TraceModel) -> TraceDetailResponse:
|
||||
"""
|
||||
Formats the trace detail response from the TraceModel instance.
|
||||
"""
|
||||
|
||||
return TraceDetailResponse(
|
||||
project_id=trace.project_id,
|
||||
trace_id=trace.trace_id,
|
||||
tags=trace.tags,
|
||||
metrics=TraceMetricsResponse.from_trace_with_metrics(trace),
|
||||
spans=[
|
||||
SpanItem(
|
||||
span_id=span.span_id,
|
||||
parent_span_id=span.parent_span_id,
|
||||
span_name=span.span_name,
|
||||
span_kind=span.span_kind,
|
||||
# span_type is inferred from span_attributes after init
|
||||
service_name=span.service_name,
|
||||
start_time=span.start_time,
|
||||
end_time=span.end_time,
|
||||
duration=span.duration,
|
||||
status_code=span.status_code,
|
||||
status_message=span.status_message,
|
||||
attributes={}, # TODO remove this
|
||||
span_attributes=span.span_attributes,
|
||||
resource_attributes=span.resource_attributes,
|
||||
event_timestamps=span.event_timestamps,
|
||||
event_names=span.event_names,
|
||||
event_attributes=span.event_attributes,
|
||||
link_trace_ids=span.link_trace_ids,
|
||||
link_span_ids=span.link_span_ids,
|
||||
link_trace_states=span.link_trace_states,
|
||||
link_attributes=span.link_attributes,
|
||||
metrics=SpanMetricsResponse.from_span_with_metrics(span)
|
||||
if has_llm_attributes(span.span_attributes)
|
||||
else None,
|
||||
freeplan_truncated=(
|
||||
# the trace has been identified as truncated and the span is beyond the limit
|
||||
self.freeplan_truncated
|
||||
or (self.freeplan_truncated and trace.spans.index(span) > FREEPLAN_SPANS_LIST_LIMIT)
|
||||
),
|
||||
)
|
||||
for span in trace.spans
|
||||
],
|
||||
freeplan_truncated=self.freeplan_truncated,
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
from typing import Optional, TypeVar, ParamSpec
|
||||
from collections import OrderedDict
|
||||
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from agentops.api.routes.v4.exceptions import InvalidParameterError
|
||||
|
||||
P = ParamSpec("P")
|
||||
R = TypeVar("R")
|
||||
|
||||
|
||||
def create_error_response(error_type: str, status_code: int, message: str, **extra_fields) -> JSONResponse:
|
||||
"""
|
||||
Create a standardized error response.
|
||||
|
||||
Args:
|
||||
error_type: Type of the error (e.g., "Invalid parameter", "Database error")
|
||||
status_code: HTTP status code
|
||||
message: Error message
|
||||
**extra_fields: Additional fields to include in the response
|
||||
|
||||
Returns:
|
||||
JSONResponse with standardized format
|
||||
"""
|
||||
# Use OrderedDict to ensure field order matches test expectations
|
||||
content = OrderedDict()
|
||||
content["error"] = error_type
|
||||
|
||||
# For InvalidParameterError, order should be error, param, message
|
||||
if "param" in extra_fields:
|
||||
content["param"] = extra_fields.pop("param")
|
||||
|
||||
content["message"] = message
|
||||
|
||||
# Add any remaining extra fields
|
||||
for key, value in extra_fields.items():
|
||||
content[key] = value
|
||||
|
||||
return JSONResponse(status_code=status_code, content=content)
|
||||
|
||||
|
||||
def validate_status_code(status_code: Optional[str]) -> Optional[str]:
|
||||
"""Validate status code parameter."""
|
||||
if not status_code:
|
||||
return None
|
||||
|
||||
valid_status_codes = ["OK", "ERROR", "UNSET"]
|
||||
if status_code not in valid_status_codes:
|
||||
raise InvalidParameterError(
|
||||
"status_code", f"Invalid status code. Expected one of: {', '.join(valid_status_codes)}."
|
||||
)
|
||||
|
||||
return status_code
|
||||
@@ -0,0 +1,121 @@
|
||||
from typing import Optional
|
||||
from abc import ABC
|
||||
from io import BytesIO
|
||||
from pydantic import BaseModel
|
||||
from fastapi import HTTPException, Depends, status
|
||||
import boto3
|
||||
from botocore.client import Config
|
||||
|
||||
from agentops.api.log_config import logger
|
||||
from agentops.api.environment import (
|
||||
SUPABASE_URL,
|
||||
SUPABASE_S3_ACCESS_KEY_ID,
|
||||
SUPABASE_S3_SECRET_ACCESS_KEY,
|
||||
)
|
||||
from agentops.api.auth import get_jwt_token, JWTPayload
|
||||
from agentops.common.route_config import BaseView
|
||||
|
||||
|
||||
_s3_client_instance: Optional[boto3.client] = None
|
||||
|
||||
|
||||
def get_s3_client() -> boto3.client:
|
||||
"""Maintain a single global instance of the S3 client"""
|
||||
global _s3_client_instance
|
||||
|
||||
if _s3_client_instance is None:
|
||||
_s3_client_instance = boto3.client(
|
||||
's3',
|
||||
endpoint_url=f"{SUPABASE_URL}/storage/v1/s3",
|
||||
aws_access_key_id=SUPABASE_S3_ACCESS_KEY_ID,
|
||||
aws_secret_access_key=SUPABASE_S3_SECRET_ACCESS_KEY,
|
||||
config=Config(signature_version='s3v4'),
|
||||
region_name='us-west-1',
|
||||
)
|
||||
return _s3_client_instance
|
||||
|
||||
|
||||
class ObjectUploadResponse(BaseModel):
|
||||
url: str
|
||||
size: int
|
||||
|
||||
|
||||
class BaseObjectUploadView(BaseView, ABC):
|
||||
"""
|
||||
Abstract base class for handling object uploads to S3-compatible storage.
|
||||
This class provides a framework for uploading objects to a storage bucket
|
||||
and generating public URLs for the uploaded objects. Subclasses must
|
||||
implement or override the `filename` property to define a unique naming
|
||||
convention for the uploaded files.
|
||||
|
||||
Attributes:
|
||||
bucket_name (str): The name of the S3 bucket where the object will be uploaded.
|
||||
max_size (int): The maximum allowed size for the uploaded object in bytes.
|
||||
Defaults to 10 MB (10 * 1024 * 1024).
|
||||
token (dict): A dictionary containing authentication or metadata
|
||||
information, such as project-specific identifiers.
|
||||
client (boto3.client): An S3 client instance for interacting with the
|
||||
storage service.
|
||||
|
||||
Methods:
|
||||
__call__() -> ObjectUploadResponse:
|
||||
Handles the upload process by reading the request body, uploading
|
||||
the object, and returning a response with the public URL and size
|
||||
of the uploaded object.
|
||||
upload_body(body: BytesIO) -> None:
|
||||
Uploads the object to the storage bucket using the provided body.
|
||||
filename() -> str:
|
||||
Generates or retrieves a unique filename for the object. This
|
||||
property must be implemented or overridden in subclasses.
|
||||
public_url() -> str:
|
||||
Generates a public URL for accessing the uploaded object.
|
||||
"""
|
||||
|
||||
bucket_name: str
|
||||
max_size: int = 25 * 1024 * 1024 # 25 MB
|
||||
|
||||
token: dict
|
||||
client: boto3.client
|
||||
|
||||
async def __call__(self, token: JWTPayload = Depends(get_jwt_token)) -> ObjectUploadResponse:
|
||||
assert self.bucket_name is not None, "`bucket_name` must be provided"
|
||||
|
||||
self.token = token
|
||||
self.client = get_s3_client()
|
||||
|
||||
body = BytesIO()
|
||||
total_size = 0
|
||||
|
||||
# read the body in chunks so we don't ever load an entire oversized file into memory
|
||||
async for chunk in self.request.stream():
|
||||
total_size += len(chunk)
|
||||
|
||||
if total_size > self.max_size:
|
||||
logger.error("Uploaded file exceeds maximum size limit")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
|
||||
detail=f"File size exceeds the maximum limit of {self.max_size} bytes",
|
||||
)
|
||||
|
||||
body.write(chunk)
|
||||
|
||||
body.seek(0)
|
||||
await self.upload_body(body)
|
||||
return ObjectUploadResponse(
|
||||
url=self.public_url,
|
||||
size=total_size,
|
||||
)
|
||||
|
||||
async def upload_body(self, body: BytesIO) -> None:
|
||||
"""Upload the object to S3."""
|
||||
self.client.upload_fileobj(body, self.bucket_name, self.filename)
|
||||
|
||||
@property
|
||||
def filename(self) -> str:
|
||||
"""Generate a unique filename for the object"""
|
||||
...
|
||||
|
||||
@property
|
||||
def public_url(self) -> str:
|
||||
"""Generate a public URL for the object"""
|
||||
return f"{SUPABASE_URL}/storage/v1/object/public/{self.bucket_name}/{self.filename}"
|
||||
@@ -0,0 +1,136 @@
|
||||
import datetime
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
|
||||
import jwt
|
||||
from tokencost import TOKEN_COSTS, count_message_tokens, count_string_tokens
|
||||
from typing_extensions import deprecated
|
||||
|
||||
from agentops.api.db.supabase_client import AsyncSupabaseClient, get_async_supabase
|
||||
from agentops.api.environment import JWT_SECRET_KEY
|
||||
from agentops.api.exceptions import ExpiredJWTError, InvalidAPIKeyError
|
||||
from agentops.api.log_config import logger
|
||||
|
||||
|
||||
@deprecated("use agentops.api.auth.generate_jwt")
|
||||
def generate_jwt(session_id, jwt_secret):
|
||||
payload = {
|
||||
"session_id": session_id,
|
||||
"exp": (
|
||||
datetime.datetime.now() + datetime.timedelta(hours=24) # Token expires in 24 hour
|
||||
).timestamp(),
|
||||
}
|
||||
token = jwt.encode(payload, jwt_secret or JWT_SECRET_KEY, algorithm="HS256")
|
||||
return token
|
||||
|
||||
|
||||
@deprecated("use agentops.api.auth.generate_jwt")
|
||||
def verify_jwt(token, secret_key):
|
||||
try:
|
||||
payload = jwt.decode(token, secret_key, algorithms=["HS256"])
|
||||
return payload["session_id"]
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise ExpiredJWTError(401, "Expired Token")
|
||||
except jwt.DecodeError:
|
||||
RuntimeError("Invalid token")
|
||||
|
||||
|
||||
def validate_uuid(uuid_string) -> uuid.UUID:
|
||||
try:
|
||||
return uuid.UUID(uuid_string, version=4)
|
||||
except ValueError:
|
||||
raise InvalidAPIKeyError(401, "Invalid API KEY format")
|
||||
except TypeError:
|
||||
raise InvalidAPIKeyError(401, "Invalid API KEY format")
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Error validating UUID: {e}")
|
||||
|
||||
|
||||
async def get_premium_status(supabase: AsyncSupabaseClient = None, user_id: str = None) -> bool:
|
||||
if supabase is None and user_id is not None:
|
||||
supabase = await get_async_supabase()
|
||||
|
||||
try:
|
||||
# return await supabase.get("users", "premium", "id", user_id)
|
||||
# TODO: when we refactor premium management, add logic here
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.warning(f"Could not fetch premium status: {e}")
|
||||
return False
|
||||
|
||||
|
||||
async def update_stats(
|
||||
supabase: AsyncSupabaseClient,
|
||||
session_id,
|
||||
cost: Decimal | None,
|
||||
events,
|
||||
prompt_tokens,
|
||||
completion_tokens,
|
||||
errors,
|
||||
):
|
||||
_current_stats = (
|
||||
await supabase.table("stats").select("*").eq("session_id", session_id).limit(1).single().execute()
|
||||
)
|
||||
if _current_stats.data:
|
||||
current_stats = _current_stats.data
|
||||
else:
|
||||
logger.error(f"Could not find stats for session {session_id}")
|
||||
return
|
||||
|
||||
current_cost = (
|
||||
Decimal(str(current_stats["cost"])) if current_stats and current_stats["cost"] else Decimal(0)
|
||||
)
|
||||
updated_cost = current_cost + (cost if cost else Decimal(0))
|
||||
updated_cost = str(updated_cost) if updated_cost != Decimal(0) else None
|
||||
|
||||
stats = {
|
||||
"session_id": session_id,
|
||||
"cost": updated_cost,
|
||||
"events": events + (current_stats["events"] if current_stats else 0),
|
||||
"prompt_tokens": prompt_tokens + (current_stats["prompt_tokens"] if current_stats else 0),
|
||||
"completion_tokens": completion_tokens + (current_stats["completion_tokens"] if current_stats else 0),
|
||||
"errors": errors + (current_stats["errors"] if current_stats else 0),
|
||||
}
|
||||
|
||||
await supabase.table("stats").upsert(stats, on_conflict="session_id").execute()
|
||||
|
||||
|
||||
def calculate_costs(model, prompt, completion):
|
||||
try:
|
||||
if model not in TOKEN_COSTS:
|
||||
raise RuntimeError(f"Model {model} not in TOKEN_COSTS")
|
||||
|
||||
# Prompt cost
|
||||
if type(prompt) == str:
|
||||
prompt_tokens = count_string_tokens(prompt, model)
|
||||
else:
|
||||
prompt_tokens = count_message_tokens(prompt, model)
|
||||
|
||||
# Completion cost
|
||||
completion_tokens = count_string_tokens(completion, model)
|
||||
|
||||
# Calculate cost
|
||||
return str(
|
||||
prompt_tokens * Decimal(str(TOKEN_COSTS[model]["input_cost_per_token"]))
|
||||
+ completion_tokens * Decimal(str(TOKEN_COSTS[model]["output_cost_per_token"]))
|
||||
)
|
||||
|
||||
except RuntimeError as e:
|
||||
logger.error(f"An error occurred while calculating cost: {e}. ")
|
||||
return 0
|
||||
|
||||
|
||||
def strip_host_env(d: dict):
|
||||
if d is None:
|
||||
return None
|
||||
|
||||
if isinstance(d, dict):
|
||||
for k in list(d.keys()): # convert dict_keys into list for in-place deletion
|
||||
if k == "host_env":
|
||||
del d[k]
|
||||
elif isinstance(d[k], dict):
|
||||
strip_host_env(d[k])
|
||||
elif isinstance(d[k], list):
|
||||
for i in d[k]:
|
||||
strip_host_env(i)
|
||||
return d
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
AgentOps Backend parent app
|
||||
|
||||
Collect app instances from all sub-apps and mount them here.
|
||||
|
||||
This allows for a single entry point for the backend, and for us to have
|
||||
domain-specific middleware for each sub-app.
|
||||
|
||||
"""
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
import sentry_sdk
|
||||
|
||||
from agentops.api.log_config import logger
|
||||
from .common.sentry import sanitize_event
|
||||
from .common.environment import API_DOMAIN
|
||||
from .common.openapi import create_combined_openapi_fn
|
||||
from .common.lifespan import lifespan
|
||||
from .auth.app import app as auth_app
|
||||
from .api.app import app as api_app
|
||||
from .opsboard.app import app as opsboard_app
|
||||
from .public.app import app as public_app
|
||||
from .deploy.app import app as deploy_app
|
||||
|
||||
__all__ = ['app']
|
||||
|
||||
sentry_sdk.init(
|
||||
traces_sample_rate=1.0,
|
||||
profiles_sample_rate=1.0,
|
||||
before_send=sanitize_event,
|
||||
)
|
||||
|
||||
# Create the main app with docs enabled in dev only
|
||||
app = FastAPI(
|
||||
title="AgentOps Backend",
|
||||
description="AgentOps Backend Services",
|
||||
docs_url="/docs" if ("localhost" in API_DOMAIN) else None,
|
||||
openapi_url="/openapi.json" if ("localhost" in API_DOMAIN) else None,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
logger.info("⚡️FastAPI app initialized")
|
||||
logger.info(f"Docs available at: {app.docs_url}" if app.docs_url else "Docs disabled")
|
||||
|
||||
# Add CORS middleware for local development
|
||||
if "localhost" in API_DOMAIN or "127.0.0.1" in API_DOMAIN:
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["http://localhost:3000", "http://127.0.0.1:3000"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
logger.info("CORS middleware enabled for local development")
|
||||
|
||||
# Configure the mounted apps
|
||||
# TODO this is redundant, but it's just for docs
|
||||
mounted_apps = {
|
||||
"/": api_app,
|
||||
# Add other mounted apps when they are enabled
|
||||
"/auth": auth_app,
|
||||
"/opsboard": opsboard_app,
|
||||
"/public": public_app,
|
||||
"/deploy": deploy_app,
|
||||
}
|
||||
|
||||
# Set the custom OpenAPI schema generator that combines all APIs
|
||||
app.openapi = create_combined_openapi_fn(
|
||||
main_app=app,
|
||||
mounted_apps=mounted_apps,
|
||||
title="AgentOps Combined API",
|
||||
version="1.0.0",
|
||||
description="Combined API for all AgentOps services",
|
||||
)
|
||||
|
||||
app.mount("/auth", auth_app)
|
||||
app.mount("/opsboard", opsboard_app)
|
||||
app.mount("/public", public_app)
|
||||
app.mount("/deploy", deploy_app)
|
||||
app.mount("/", api_app)
|
||||
|
||||
|
||||
if "localhost" not in API_DOMAIN:
|
||||
# only run Sentry in prod since it breaks the docs routes.
|
||||
from sentry_sdk.integrations.asgi import SentryAsgiMiddleware
|
||||
|
||||
logger.info("Sentry middleware enabled")
|
||||
app = SentryAsgiMiddleware(app)
|
||||
@@ -0,0 +1,123 @@
|
||||
# AgentOps Authentication System
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
The AgentOps authentication system combines Supabase for identity management with a Redis-backed session store. Authentication flows begin when users authenticate through Supabase, which returns JWT tokens containing user information. Our system then creates its own session, stores the mapping in Redis, and issues an HTTP-only cookie containing a signed session identifier. This approach provides the security benefits of server-side sessions while leveraging Supabase's robust identity platform.
|
||||
|
||||
## Session Management
|
||||
|
||||
The `Session` class provides a clean interface to the Redis backend. Each session is identified by a UUID and contains a reference to the authenticated user. The interface is deliberately minimal:
|
||||
|
||||
Server-side session storage was chosen over client-side JWT tokens because it allows for immediate session invalidation and extension, neither of which is possible with self-contained JWTs. The Redis backend provides fast access with automatic TTL management.
|
||||
|
||||
## Authentication Flow
|
||||
|
||||
The authentication flow consists of two distinct steps, designed to securely handle Supabase tokens:
|
||||
|
||||
1. The `auth_callback` view receives the hash fragment from Supabase (containing access and refresh tokens) and renders a page with strict Content-Security-Policy that extracts these tokens.
|
||||
|
||||
2. The client-side JavaScript forwards these tokens to `auth_session`, which validates the Supabase JWT, creates a new session, and sets a secure HTTP-only cookie containing our signed session ID.
|
||||
|
||||
This approach prevents tokens from appearing in server logs or browser history, reducing the risk of token leakage.
|
||||
|
||||
## Request Authentication
|
||||
|
||||
All API endpoints require authentication by default through the `AuthenticatedRoute` class. Only routes explicitly marked with the `@public_route` decorator are accessible without authentication. This "secure by default" pattern prevents accidentally exposing sensitive endpoints.
|
||||
|
||||
The middleware extracts the session cookie, validates it, retrieves the session from Redis, and provides it to the route handler via `request.state.session`. When enabled, session expiration is automatically extended on each authenticated request.
|
||||
|
||||
## Security Considerations
|
||||
|
||||
The security model specifically avoids client-side JWTs because they cannot be invalidated, their expiration cannot be extended, and they present risks if stored in localStorage. Instead, HTTP-only cookies with the Secure and SameSite=strict flags prevent JavaScript access and CSRF attacks.
|
||||
|
||||
Content Security Policy with nonces is implemented on authentication pages to prevent XSS attacks, and all cookies are scoped to specific domains to limit exposure. The session store architecture allows for immediate invalidation of all sessions if needed.
|
||||
|
||||
## Cookie Management
|
||||
|
||||
The authentication system uses a minimalist cookie approach to maintain user sessions securely. Understanding how these cookies work is important for developers integrating with the AgentOps API.
|
||||
|
||||
### How Session Cookies Work
|
||||
|
||||
When a user authenticates:
|
||||
|
||||
1. A server-side session is created and stored in Redis
|
||||
2. A session identifier (UUID) is generated
|
||||
3. This identifier is JWT-encoded with our internal secret
|
||||
4. The encoded token is stored in an HTTP-only cookie
|
||||
|
||||
For subsequent requests:
|
||||
|
||||
1. The cookie is automatically sent with each request to the API
|
||||
2. The middleware extracts and validates the cookie
|
||||
3. The session ID is decoded and used to retrieve the full session from Redis
|
||||
4. If authentication is successful, the session object is made available to the endpoint handler
|
||||
|
||||
### Cookie Properties
|
||||
|
||||
Our session cookies are configured with several important security properties:
|
||||
|
||||
- **HTTP-only**: Cannot be accessed by JavaScript, protecting against XSS attacks
|
||||
- **Secure**: Only sent over HTTPS in production environments
|
||||
- **SameSite=strict**: Only sent for same-site requests, preventing CSRF attacks
|
||||
- **Domain-scoped**: Limited to the API domain
|
||||
- **Expiration**: Automatically expires after the configured session lifetime
|
||||
|
||||
### Client Integration Considerations
|
||||
|
||||
When developing a client application that interacts with AgentOps:
|
||||
|
||||
- There's no need to manually extract or send tokens - browsers handle cookies automatically
|
||||
- Authentication state persists across page reloads as long as the session is valid
|
||||
- Logging out requires an explicit call to the logout endpoint, which clears the cookie
|
||||
- Cross-domain requests require credentials: `credentials: 'include'` (fetch) or `withCredentials: true` (axios)
|
||||
- Mobile apps and non-browser clients need to handle cookies appropriately for their platform
|
||||
|
||||
### Cross-Origin and SameSite Cookies
|
||||
|
||||
The API server includes CORS configuration that allows requests from the main application domain (`APP_DOMAIN`). This works with SameSite=strict cookies through the following mechanism:
|
||||
|
||||
- The CORS `allow_origins` list includes the main application URL (`APP_URL`)
|
||||
- The `allow_credentials` flag is set to `True`, permitting cookies to be included in cross-origin requests
|
||||
- Clients must explicitly include credentials in their requests
|
||||
- The browser will then include cookies with cross-origin requests to trusted domains
|
||||
|
||||
## Implementing Authentication in an Application
|
||||
|
||||
The `AuthenticatedRoute` class enforces authentication for all endpoints by default, while the `@public_route` decorator allows specific endpoints to be accessible without authentication.
|
||||
|
||||
```python
|
||||
from fastapi import FastAPI, APIRouter, Request
|
||||
from uuid import UUID
|
||||
from agentops.auth.middleware import AuthenticatedRoute
|
||||
from agentops.auth.views import public_route
|
||||
from agentops.auth.session import Session
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
# Create a router with the AuthenticatedRoute class
|
||||
router = APIRouter(route_class=AuthenticatedRoute)
|
||||
|
||||
# Protected endpoint (requires authentication)
|
||||
@router.get("/protected-endpoint")
|
||||
async def protected_endpoint(request: Request):
|
||||
session: Session = request.state.session
|
||||
user_id: UUID = session.user_id
|
||||
return {"message": f"Hello, user {str(user_id)}!"}
|
||||
|
||||
# Public endpoint (no authentication required)
|
||||
@router.get("/public-endpoint")
|
||||
@public_route
|
||||
async def public_endpoint():
|
||||
return {"message": "This endpoint is accessible without authentication"}
|
||||
|
||||
# Include the router in your application
|
||||
app.include_router(router)
|
||||
```
|
||||
|
||||
With this implementation:
|
||||
|
||||
1. All routes on the router require authentication by default
|
||||
2. The middleware extracts and validates the session cookie from requests
|
||||
3. For authenticated endpoints, `request.state.session` is populated with the user's session
|
||||
4. Session expiration is automatically extended when enabled
|
||||
5. Routes with the `@public_route` decorator are accessible without authentication
|
||||
@@ -0,0 +1,94 @@
|
||||
from fastapi import FastAPI, APIRouter
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from agentops.common.route_config import RouteConfig, register_routes
|
||||
from agentops.common.middleware import CacheControlMiddleware, ExceptionMiddleware
|
||||
from agentops.common.environment import ALLOWED_ORIGINS
|
||||
|
||||
from .middleware import AuthenticatedRoute
|
||||
from .views import (
|
||||
auth_callback,
|
||||
auth_code,
|
||||
auth_session,
|
||||
auth_login,
|
||||
auth_otp,
|
||||
auth_oauth,
|
||||
auth_signup,
|
||||
auth_password_reset,
|
||||
auth_logout,
|
||||
)
|
||||
|
||||
__all__ = ['app']
|
||||
|
||||
route_config: list[RouteConfig] = [
|
||||
RouteConfig(
|
||||
name='auth_callback',
|
||||
path="/callback",
|
||||
endpoint=auth_callback,
|
||||
methods=["GET"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='auth_code',
|
||||
path="/code",
|
||||
endpoint=auth_code,
|
||||
methods=["GET"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='auth_session',
|
||||
path="/session",
|
||||
endpoint=auth_session,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='auth_login',
|
||||
path="/login",
|
||||
endpoint=auth_login,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='auth_otp',
|
||||
path="/otp",
|
||||
endpoint=auth_otp,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='auth_oauth',
|
||||
path="/oauth",
|
||||
endpoint=auth_oauth,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='auth_signup',
|
||||
path="/signup",
|
||||
endpoint=auth_signup,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='auth_password_reset',
|
||||
path="/password_reset",
|
||||
endpoint=auth_password_reset,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='auth_logout',
|
||||
path="/logout",
|
||||
endpoint=auth_logout,
|
||||
methods=["POST"],
|
||||
),
|
||||
]
|
||||
|
||||
app = FastAPI(title="AgentOps Auth")
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=ALLOWED_ORIGINS,
|
||||
allow_credentials=True,
|
||||
allow_methods=['GET', 'POST', 'OPTIONS'],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
app.add_middleware(CacheControlMiddleware)
|
||||
app.add_middleware(ExceptionMiddleware)
|
||||
|
||||
router = APIRouter(route_class=AuthenticatedRoute)
|
||||
register_routes(router, route_config, prefix="/auth")
|
||||
app.include_router(router)
|
||||
@@ -0,0 +1,38 @@
|
||||
import os
|
||||
from agentops.api.log_config import logger
|
||||
|
||||
# generate an AUTH_COOKIE_SECRET with:
|
||||
# import secrets; print(secrets.token_hex(32))
|
||||
_DEV_AUTH_COOKIE_SECRET = "your_cookie_signing_secret"
|
||||
AUTH_COOKIE_SECRET = os.getenv("AUTH_COOKIE_SECRET", _DEV_AUTH_COOKIE_SECRET)
|
||||
|
||||
AUTH_COOKIE_NAME = os.getenv("AUTH_COOKIE_NAME", "session_id")
|
||||
AUTH_JWT_ALGO = "HS256" # this is for our internal JWT on the session cookie
|
||||
|
||||
|
||||
# Sessions are extended on every interaction with the API. This means a user
|
||||
# won't need to log in again as long as they interact with the API at least once
|
||||
# every 7 days, for up to 30 days while the cookie remains valid.
|
||||
|
||||
# extend sessions on every interaction
|
||||
AUTH_EXTEND_SESSIONS: bool = True
|
||||
# session expiry relates to the record stored in the cache backend
|
||||
AUTH_SESSION_EXPIRY = 60 * 60 * 24 * 7 # 7 days in seconds
|
||||
# cookie expiry relates to the cookie stored in the browser
|
||||
AUTH_COOKIE_EXPIRY = 60 * 60 * 24 * 30 # 30 days in seconds
|
||||
|
||||
SUPABASE_JWT_SECRET: str = os.getenv("JWT_SECRET_KEY")
|
||||
|
||||
|
||||
if AUTH_COOKIE_SECRET == _DEV_AUTH_COOKIE_SECRET:
|
||||
logger.warning("[agentops.auth.environment] Using an unsafe AUTH_COOKIE_SECRET")
|
||||
|
||||
if not SUPABASE_JWT_SECRET:
|
||||
logger.warning("[agentops.auth.environment] No JWT_SECRET_KEY set")
|
||||
|
||||
|
||||
AUTH_ADDITIONAL_REFERERS = [
|
||||
# Add any additional referers that should be allowed to access the auth app
|
||||
"https://accounts.google.com/",
|
||||
"https://github.com/",
|
||||
]
|
||||
@@ -0,0 +1,35 @@
|
||||
from fastapi import HTTPException
|
||||
import gotrue
|
||||
|
||||
|
||||
class AuthException(HTTPException):
|
||||
"""Shared status_code for all auth exceptions"""
|
||||
|
||||
# TODO don't return detailed messages to the client in production
|
||||
def __init__(self, detail: str = "Failed to authenticate user."):
|
||||
super().__init__(status_code=401, detail=detail)
|
||||
|
||||
@classmethod
|
||||
def from_gotrue_autherror(cls, exc: gotrue.errors.AuthApiError):
|
||||
"""
|
||||
Create an AuthException from a GoTrue exception.
|
||||
|
||||
This let's us handle explicit messaging to the user and prevents printing
|
||||
all exception messages to the user.
|
||||
"""
|
||||
if exc.message == "Email not confirmed":
|
||||
return AuthUnconfirmedEmailException()
|
||||
return cls() # don't bubble messages we don't explicitly approve
|
||||
|
||||
|
||||
class AuthUnconfirmedEmailException(AuthException):
|
||||
"""Raised when the user has not confirmed their email address"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
detail=(
|
||||
"Your email address has not been confirmed. "
|
||||
"Check your inbox for a confirmation email and click the link "
|
||||
"before signing in for the first time."
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,73 @@
|
||||
from collections.abc import Callable
|
||||
from fastapi import Request, Response
|
||||
from fastapi.routing import APIRoute
|
||||
|
||||
from .environment import (
|
||||
AUTH_EXTEND_SESSIONS,
|
||||
AUTH_COOKIE_NAME,
|
||||
)
|
||||
from .exceptions import AuthException
|
||||
from .session import Session
|
||||
from .views import _decode_session_cookie
|
||||
|
||||
|
||||
class AuthenticatedRoute(APIRoute):
|
||||
"""
|
||||
Route class that enforces authentication for endpoints.
|
||||
|
||||
Protects all endpoints except those explicitly marked as public.
|
||||
|
||||
Populates request.state.session with the user's Session object.
|
||||
|
||||
Usage:
|
||||
from fastapi import FastAPI, APIRouter
|
||||
from api.agentops.auth.middleware import AuthenticatedRoute
|
||||
|
||||
app = FastAPI()
|
||||
router = APIRouter(route_class=AuthenticatedRoute)
|
||||
app.include_router(router)
|
||||
...
|
||||
"""
|
||||
|
||||
def _get_session(self, request: Request) -> Session:
|
||||
"""
|
||||
Get the user's session from the request.
|
||||
|
||||
Raises AuthException if the user is not authenticated or if the session has expired.
|
||||
|
||||
If AUTH_EXTEND_SESSIONS is enabled, the session expiry is extended.
|
||||
"""
|
||||
if not (cookie := request.cookies.get(AUTH_COOKIE_NAME)):
|
||||
raise AuthException("User is not authenticated.")
|
||||
|
||||
if not (session := _decode_session_cookie(cookie)):
|
||||
raise AuthException("User's session has expired.")
|
||||
|
||||
if AUTH_EXTEND_SESSIONS:
|
||||
session.extend()
|
||||
|
||||
return session
|
||||
|
||||
def get_route_handler(self) -> Callable:
|
||||
"""
|
||||
Override the default route handler to inject authentication logic.
|
||||
|
||||
This method wraps the original route handler to ensure that the session
|
||||
is populated in request.state.session before calling the handler.
|
||||
|
||||
If the endpoint is marked as public, it will not raise an AuthException
|
||||
when the session is not found or invalid.
|
||||
"""
|
||||
original_route_handler = super().get_route_handler()
|
||||
|
||||
async def custom_route_handler(request: Request) -> Response:
|
||||
try:
|
||||
request.state.session = self._get_session(request)
|
||||
except AuthException as e:
|
||||
if not getattr(self.endpoint, 'is_public', False):
|
||||
raise e
|
||||
|
||||
response = await original_route_handler(request)
|
||||
return response
|
||||
|
||||
return custom_route_handler
|
||||
@@ -0,0 +1,84 @@
|
||||
from typing import Literal
|
||||
import pydantic
|
||||
|
||||
|
||||
class BaseSchema(pydantic.BaseModel):
|
||||
"""
|
||||
Base schema type intended to be used for creating input schemas.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class BaseResponse(BaseSchema):
|
||||
"""
|
||||
Base response type intended to be directly populated by a sqlalchemy model.
|
||||
"""
|
||||
|
||||
model_config = pydantic.ConfigDict(
|
||||
from_attributes=True,
|
||||
)
|
||||
|
||||
|
||||
class StatusResponse(BaseResponse):
|
||||
"""
|
||||
Status response type intended to be used for simple success/failure responses.
|
||||
"""
|
||||
|
||||
success: bool = True
|
||||
message: str | None = None
|
||||
|
||||
|
||||
class RedirectMessageResponse(StatusResponse):
|
||||
"""
|
||||
Response type for redirecting to a specific URL.
|
||||
"""
|
||||
|
||||
url: str
|
||||
|
||||
|
||||
class LoginSchema(BaseSchema):
|
||||
"""
|
||||
Schema for login data.
|
||||
"""
|
||||
|
||||
email: str
|
||||
password: str
|
||||
|
||||
|
||||
class OTPSchema(BaseSchema):
|
||||
"""
|
||||
Schema for the request to send a one-time password (OTP) to the user's email.
|
||||
"""
|
||||
|
||||
email: str
|
||||
|
||||
|
||||
OAuthProvider = Literal["google", "github"]
|
||||
|
||||
|
||||
class OAuthSchema(BaseSchema):
|
||||
"""
|
||||
Schema for the request to initiate OAuth login.
|
||||
"""
|
||||
|
||||
provider: OAuthProvider
|
||||
redirect_to: str | None = None
|
||||
|
||||
|
||||
class SignupSchema(BaseSchema):
|
||||
"""
|
||||
Schema for user signup data.
|
||||
"""
|
||||
|
||||
email: str
|
||||
password: str
|
||||
full_name: str
|
||||
|
||||
|
||||
class PasswordResetSchema(BaseSchema):
|
||||
"""
|
||||
Schema for the request to reset a user's password.
|
||||
"""
|
||||
|
||||
email: str
|
||||
@@ -0,0 +1,93 @@
|
||||
from typing import Optional
|
||||
from dataclasses import dataclass
|
||||
from uuid import uuid4, UUID
|
||||
|
||||
from agentops.common import cache
|
||||
from .environment import AUTH_SESSION_EXPIRY
|
||||
|
||||
|
||||
def _make_key(session_id: str | UUID) -> str:
|
||||
"""Generate a cache key for a session ID."""
|
||||
return f"agentops.session:{session_id}"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Session:
|
||||
"""
|
||||
User session management using a cache backend.
|
||||
|
||||
This class provides methods for creating, retrieving, extending, and expiring
|
||||
user sessions, with each session associating a unique session ID with a user ID.
|
||||
Sessions are stored in the cache with a configurable expiry time (AUTH_SESSION_EXPIRY).
|
||||
|
||||
Usage:
|
||||
```python
|
||||
# Create a new session
|
||||
session = Session.create(user_id=user.id)
|
||||
|
||||
# Get an existing session
|
||||
if session := Session.get(session_id):
|
||||
# Session is valid, user is authenticated
|
||||
user_id = session.user_id
|
||||
|
||||
# Extend session expiry
|
||||
session.extend()
|
||||
|
||||
# Log out by expiring the session
|
||||
session.expire()
|
||||
```
|
||||
"""
|
||||
|
||||
session_id: UUID
|
||||
user_id: UUID
|
||||
|
||||
@classmethod
|
||||
def get(cls, session_id: str | UUID) -> Optional['Session']:
|
||||
"""
|
||||
Retrieve a session by its ID.
|
||||
|
||||
Args:
|
||||
session_id (str | UUID): The session ID to look up
|
||||
|
||||
Returns:
|
||||
Optional[Session]: Session object if found, None otherwise
|
||||
"""
|
||||
session_id = str(session_id)
|
||||
if user_id := cache.get(_make_key(session_id)):
|
||||
return cls(
|
||||
session_id=UUID(session_id),
|
||||
user_id=UUID(user_id),
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def create(cls, user_id: UUID) -> 'Session':
|
||||
"""
|
||||
Create a new session for a user.
|
||||
|
||||
Args:
|
||||
user_id (UUID): The user ID to associate with the session
|
||||
|
||||
Returns:
|
||||
Session: The newly created session
|
||||
"""
|
||||
session = cls(uuid4(), user_id)
|
||||
cache.setex(_make_key(session.session_id), AUTH_SESSION_EXPIRY, str(session.user_id))
|
||||
return session
|
||||
|
||||
def extend(self) -> None:
|
||||
"""
|
||||
Extend the session's expiry time.
|
||||
|
||||
Resets the expiry time to AUTH_SESSION_EXPIRY seconds from now.
|
||||
"""
|
||||
return cache.expire(_make_key(self.session_id), AUTH_SESSION_EXPIRY)
|
||||
|
||||
def expire(self) -> None:
|
||||
"""
|
||||
Delete the session from the cache.
|
||||
|
||||
Used for logout operations or to invalidate a session.
|
||||
"""
|
||||
return cache.delete(_make_key(self.session_id))
|
||||
@@ -0,0 +1,66 @@
|
||||
{#
|
||||
Auth Callback Handler
|
||||
|
||||
Supabase redirects to this page after authentication.
|
||||
|
||||
We process the parameters in JavaScript because they are only present on the URL
|
||||
hash, which prevents it from ever being leaked in logs and to proxies, but means
|
||||
that it is not accessible by the server.
|
||||
|
||||
CSP is enforced as strictly as possible by passing a random nonce to the body and
|
||||
via the `Content-Security-Policy` header that only allows the script inside this
|
||||
template, as marked by the nonce, to run. No external scripts are allowed.
|
||||
(Note that if there is ever a need to load external content into this page, the CSP
|
||||
policies we have in place will need to be re-evaluated.)
|
||||
|
||||
`window.location.hash` must *always* be called when this page is loaded to prevent
|
||||
sensitive data in the URL from being stored in the browser history.
|
||||
|
||||
We also set the `Referrer-Policy` header to `no-referrer` to prevent the
|
||||
browser from sending the URL of this page to the next page, just in case.
|
||||
|
||||
Given these constraints, the only way to leak sensitive data is if the user
|
||||
has a malicious browser extension that reads the URL and sends it to an attacker,
|
||||
or if the user manually copies and pastes the URL.
|
||||
|
||||
#}
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Logging in...</title>
|
||||
<meta http-equiv="Referrer-Policy" content="no-referrer">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<script nonce="{{ nonce }}">
|
||||
(async () => {
|
||||
if (location.hash) {
|
||||
try {
|
||||
const response = await fetch('{{ auth_session_url }}', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: location.hash.slice(1),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('Failed to create session:', response.status);
|
||||
// Redirect to signin with error message
|
||||
window.location.replace('/signin?error=session_creation_failed');
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error creating session:', error);
|
||||
window.location.replace('/signin?error=session_creation_error');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
window.location.replace('{{ dashboard_url }}');
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
@@ -0,0 +1,557 @@
|
||||
# HTTP only cookie- allowed to be accessed during requests only; not accessible to javascript
|
||||
# set to agentops.ai domain to share across subdomains
|
||||
# store session ID in cookie, reference central session store (redis?)
|
||||
# extend session expiration +30 mins when it is used to extend login
|
||||
# require MFA when editing sensitive information
|
||||
|
||||
# supabase returns the tokens as part of the URL hash, which makes them harder to leak;
|
||||
# they won't show up in logs/proxies/etc but we must call window.location.replace to
|
||||
# remove them from the browser history
|
||||
|
||||
# we use the returned hash params to query the supabase backed which returns a
|
||||
# Supabase JWT, containing the user_id, among other fields.
|
||||
# after validating that JWT, we create our own session ID, store it in the session
|
||||
# store backend, and then JWT-encode the session_id before storing it as an
|
||||
# HTTP-only cookie
|
||||
|
||||
# since we host the auth callback on the api subdomain it doesn't need to live
|
||||
# across domains
|
||||
|
||||
## Reasons for not using client-side JWTs
|
||||
# JWT stores session state client-side, so avoids central session store
|
||||
# can be accessed from javascript if stored in local storage
|
||||
# JWTs can be signed to prevent tampering, but not encrypted
|
||||
# JWTs can be set to expire after a certain amount of time, but not extendable,
|
||||
# not invalidatable from a central location
|
||||
# can be used across domains, which is useful but also XSS risk
|
||||
from typing import Union, Callable, Optional
|
||||
import os
|
||||
from functools import wraps
|
||||
import inspect
|
||||
import base64
|
||||
import uuid
|
||||
import jwt
|
||||
from pathlib import Path
|
||||
import urllib.parse
|
||||
|
||||
import pydantic
|
||||
from fastapi import Request, Response
|
||||
from fastapi.exceptions import HTTPException
|
||||
from fastapi.responses import JSONResponse, HTMLResponse, RedirectResponse
|
||||
from jinja2 import Environment, FileSystemLoader
|
||||
import gotrue
|
||||
|
||||
from agentops.api.log_config import logger
|
||||
from agentops.common.route_config import reverse_path, BaseView
|
||||
from agentops.common.environment import DASHBOARD_URL, API_DOMAIN, API_URL, APP_URL
|
||||
from agentops.common import rate_limit
|
||||
from agentops.api.db.supabase_client import get_supabase # TODO move this
|
||||
|
||||
from .environment import (
|
||||
SUPABASE_JWT_SECRET,
|
||||
AUTH_COOKIE_SECRET,
|
||||
AUTH_COOKIE_NAME,
|
||||
AUTH_COOKIE_EXPIRY,
|
||||
AUTH_JWT_ALGO,
|
||||
AUTH_ADDITIONAL_REFERERS,
|
||||
)
|
||||
from .schemas import (
|
||||
StatusResponse,
|
||||
RedirectMessageResponse,
|
||||
LoginSchema,
|
||||
OTPSchema,
|
||||
OAuthProvider,
|
||||
OAuthSchema,
|
||||
SignupSchema,
|
||||
PasswordResetSchema,
|
||||
)
|
||||
from .exceptions import AuthException
|
||||
from .session import Session
|
||||
|
||||
TEMPLATE_DIR = Path(__file__).parent / "templates"
|
||||
templates = Environment(loader=FileSystemLoader(TEMPLATE_DIR))
|
||||
|
||||
|
||||
_all__ = [
|
||||
'public_route',
|
||||
'auth_callback',
|
||||
'auth_code',
|
||||
'auth_session',
|
||||
'auth_login',
|
||||
'auth_otp',
|
||||
'auth_oauth',
|
||||
'auth_signup',
|
||||
'auth_password_reset',
|
||||
'auth_logout',
|
||||
]
|
||||
|
||||
|
||||
OAUTH_SCOPES: dict[OAuthProvider, str] = {
|
||||
'github': "read:user user:email",
|
||||
'google': "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
|
||||
}
|
||||
# don't redirect to these pages after login/signup; this prevents from returning users
|
||||
# to the signin page if that's where they started
|
||||
REDIRECT_OVERRIDES = (
|
||||
"/signin",
|
||||
"/signup",
|
||||
)
|
||||
|
||||
|
||||
def _get_api_domain() -> str:
|
||||
"""
|
||||
Removes the port from the development domain.
|
||||
"""
|
||||
return API_DOMAIN.split(':')[0]
|
||||
|
||||
|
||||
class SupabaseUserData(pydantic.BaseModel):
|
||||
"""
|
||||
Dataclass for data extracted from a Supabase JWT.
|
||||
"""
|
||||
|
||||
model_config = {'extra': 'ignore'}
|
||||
|
||||
iss: Optional[str] = None # Issuer: The URL of your Supabase project (optional for local dev)
|
||||
sub: str # Subject: The user's UUID
|
||||
iat: int # Issued At: When the token was created
|
||||
exp: int # Expiration Time: When the token expires
|
||||
aud: str # Audience: Usually "authenticated"
|
||||
|
||||
email: str # The user's email address
|
||||
role: str # The user's role (typically "authenticated")
|
||||
app_metadata: dict # Contains information like the provider used for authentication
|
||||
user_metadata: dict # Custom data associated with the user, such as their name
|
||||
session_id: str # A unique identifier for the current session
|
||||
|
||||
|
||||
def _decode_supabase_jwt(token: str) -> SupabaseUserData:
|
||||
"""
|
||||
Decode the Supabase JWT to get the available data about the authenticated user.
|
||||
"""
|
||||
# Add leeway to account for clock skew between Supabase and our server
|
||||
user_info = jwt.decode(
|
||||
token, SUPABASE_JWT_SECRET, algorithms=['HS256'], audience="authenticated", leeway=10
|
||||
)
|
||||
return SupabaseUserData(**user_info)
|
||||
|
||||
|
||||
def _encode_session_cookie(session: Session) -> str:
|
||||
"""
|
||||
Encode the session as a JWT for use in setting our own session cookie.
|
||||
|
||||
Currently this just includes the session_id in order to avoid storing any
|
||||
sensitive information in the cookie.
|
||||
"""
|
||||
session_id = str(session.session_id)
|
||||
return jwt.encode({"session_id": session_id}, AUTH_COOKIE_SECRET, algorithm=AUTH_JWT_ALGO)
|
||||
|
||||
|
||||
def _decode_session_cookie(cookie: str) -> Session | None:
|
||||
"""
|
||||
Decode the session cookie to get the Session object.
|
||||
Raises AuthException if the cookie is invalid or expired.
|
||||
Returns None if the session is not found.
|
||||
"""
|
||||
try:
|
||||
data = jwt.decode(cookie, AUTH_COOKIE_SECRET, algorithms=[AUTH_JWT_ALGO])
|
||||
return Session.get(data['session_id'])
|
||||
except (KeyError, jwt.InvalidTokenError):
|
||||
raise AuthException("Could not decode internal session JWT.")
|
||||
|
||||
|
||||
def _validate_request(request: Request) -> None:
|
||||
"""
|
||||
Validate the request to lock down public roues; 100% security through
|
||||
obscurity, but better than nothing.
|
||||
"""
|
||||
|
||||
if 'localhost' in API_URL:
|
||||
# Bypass all checks in local development
|
||||
return
|
||||
|
||||
# Railway always sets the x-forwarded-for header, so we can use that to get the
|
||||
# original IP address of the request. This should never be empty, but maybe our
|
||||
# IP address gets exposed and someone makes a direct request to the API?
|
||||
forwarded_for = request.headers.get("x-forwarded-for")
|
||||
if not forwarded_for:
|
||||
logger.error("Request was made to a public route without a forwarded IP address.")
|
||||
raise HTTPException(500)
|
||||
|
||||
# Rate limit the request based on the forwarded IP address
|
||||
rate_limit.record_interaction(forwarded_for)
|
||||
if rate_limit.is_blocked(forwarded_for):
|
||||
logger.warning(f"Rate limit exceeded for IP: {forwarded_for}")
|
||||
raise HTTPException(429)
|
||||
|
||||
# Check if the request was made to the correct host. This is also set by
|
||||
# Railway, but we should check it anyway.
|
||||
forwarded_host = request.headers.get("x-forwarded-host")
|
||||
if forwarded_host != API_DOMAIN:
|
||||
logger.error(f"Request was made to a public route from an unexpected host: {forwarded_host}")
|
||||
raise HTTPException(500)
|
||||
|
||||
# Check if the Origin header is present
|
||||
# If this is missing this is a strong indicator we are being accessed outside a browser
|
||||
origin = request.headers.get("origin")
|
||||
if origin and not origin.startswith(APP_URL):
|
||||
logger.warning(f"Request was made to a public route from an unexpected origin: {origin}")
|
||||
raise HTTPException(500)
|
||||
|
||||
# Check if the referrer header is present
|
||||
# If this is missing this is a strong indicator we are being accessed outside a browser
|
||||
referrer = request.headers.get("referer")
|
||||
if referrer and not any(referrer.startswith(u) for u in (APP_URL, *AUTH_ADDITIONAL_REFERERS)):
|
||||
logger.warning(f"Request was made to a public route from an unexpected referrer: {referrer}")
|
||||
raise HTTPException(500)
|
||||
|
||||
# Check for a user agent header.
|
||||
# If this is missing this is a strong indicator we are being accessed outside a browser
|
||||
user_agent = request.headers.get("user-agent")
|
||||
if not user_agent:
|
||||
logger.warning(f"Request was made to a public route from an unexpected user agent: {user_agent}")
|
||||
raise HTTPException(500)
|
||||
|
||||
|
||||
def public_route(decorated: Union[Callable, type[BaseView]]) -> Union[Callable, type[BaseView]]:
|
||||
"""
|
||||
Mark a route as public.
|
||||
|
||||
We default to requiring authentication on all routes unless they are
|
||||
explicitly marked as public. This is enforced by the middleware.
|
||||
|
||||
Can be applied to functions or BaseView classes.
|
||||
"""
|
||||
|
||||
if inspect.isclass(decorated):
|
||||
# class based views
|
||||
if not issubclass(decorated, BaseView):
|
||||
raise TypeError(f"Class {decorated.__name__} must inherit from BaseView to use @public_route")
|
||||
|
||||
view_func = decorated.__call__
|
||||
|
||||
@wraps(view_func)
|
||||
async def wrapper(self, *args, **kwargs):
|
||||
# for BaseView, request is available as self.request
|
||||
_validate_request(self.request)
|
||||
return await view_func(self, *args, **kwargs)
|
||||
|
||||
wrapper.is_public = True
|
||||
decorated.__call__ = wrapper
|
||||
return decorated
|
||||
else:
|
||||
# function-based views
|
||||
@wraps(decorated)
|
||||
async def wrapper(*args, **kwargs):
|
||||
# for functions, request comes from kwargs
|
||||
request = kwargs.get('request')
|
||||
assert request is not None, "`Request` must be available to views decorated with `@public_route`"
|
||||
_validate_request(request)
|
||||
return await decorated(*args, **kwargs)
|
||||
|
||||
wrapper.is_public = True
|
||||
return wrapper
|
||||
|
||||
|
||||
@public_route
|
||||
async def auth_callback(request: Request) -> HTMLResponse:
|
||||
"""
|
||||
Serves the authentication callback page, which captures the tokens from the URL hash
|
||||
and forwards them to our auth_session endpoint.
|
||||
|
||||
This view just serves the HTML page, which is a simple JavaScript app that
|
||||
captures the tokens from the URL hash and forwards them to our auth_session endpoint.
|
||||
"""
|
||||
# Content Security Policy headers prevent any scripts from running on the page,
|
||||
# except those with the correct nonce
|
||||
nonce = base64.b64encode(os.urandom(32)).decode('utf-8')
|
||||
headers = {
|
||||
'Content-Security-Policy': f"script-src 'nonce-{nonce}'",
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
}
|
||||
|
||||
# Check if there's a redirect_to parameter in the query string
|
||||
redirect_to = request.query_params.get('redirect_to')
|
||||
|
||||
# If no explicit redirect_to, check for invite parameter to construct the redirect
|
||||
if not redirect_to:
|
||||
invite_org_id = request.query_params.get('invite')
|
||||
if invite_org_id:
|
||||
redirect_to = f"{APP_URL}/settings/organization?invite={invite_org_id}"
|
||||
else:
|
||||
redirect_to = DASHBOARD_URL
|
||||
|
||||
# Ensure the redirect URL is to our app domain for security
|
||||
if not redirect_to.startswith(APP_URL):
|
||||
redirect_to = DASHBOARD_URL
|
||||
|
||||
template = templates.get_template('auth_callback.html')
|
||||
content = template.render(
|
||||
nonce=nonce, auth_session_url=reverse_path('auth_session'), dashboard_url=redirect_to
|
||||
)
|
||||
|
||||
return HTMLResponse(content=content, headers=headers)
|
||||
|
||||
|
||||
def _create_session_for_response(response: Response, access_token: str) -> Response:
|
||||
"""
|
||||
Create a session for the user based on the access token and set the session cookie in the response.
|
||||
"""
|
||||
user_data: SupabaseUserData = _decode_supabase_jwt(access_token)
|
||||
user_id = uuid.UUID(user_data.sub)
|
||||
|
||||
session = Session.create(user_id)
|
||||
|
||||
cookie_value = _encode_session_cookie(session)
|
||||
|
||||
cookie_domain = _get_api_domain()
|
||||
# Use secure cookies only with HTTPS
|
||||
cookie_secure = 'https' in API_URL
|
||||
# Use 'lax' for HTTP (development) to allow cross-origin requests, 'strict' for HTTPS (production)
|
||||
cookie_samesite = "lax" if not cookie_secure else "strict"
|
||||
|
||||
response.set_cookie(
|
||||
key=AUTH_COOKIE_NAME,
|
||||
value=cookie_value,
|
||||
httponly=True, # not accessible to JavaScript
|
||||
secure=cookie_secure, # only send over https in production
|
||||
domain=cookie_domain, # set cookie for the api domain
|
||||
max_age=AUTH_COOKIE_EXPIRY,
|
||||
samesite=cookie_samesite,
|
||||
path="/", # valid across all paths
|
||||
)
|
||||
|
||||
return response
|
||||
|
||||
|
||||
@public_route
|
||||
async def auth_code(request: Request, code: str) -> RedirectResponse:
|
||||
"""
|
||||
Handles the OAuth callback by exchanging the authorization code for a session.
|
||||
This is the endpoint that the OAuth provider redirects to after the user has authenticated.
|
||||
It expects a 'code' parameter in the query string, which is the authorization code
|
||||
received from the OAuth provider.
|
||||
"""
|
||||
supabase_client = get_supabase()
|
||||
|
||||
try:
|
||||
auth_response = supabase_client.auth.exchange_code_for_session({'auth_code': code})
|
||||
except gotrue.errors.AuthApiError as e:
|
||||
raise AuthException.from_gotrue_autherror(e)
|
||||
|
||||
if hasattr(auth_response, 'error'):
|
||||
raise AuthException("Failed to exchange code for session.")
|
||||
|
||||
access_token = auth_response.session.access_token
|
||||
|
||||
# TODO this often redirects back to the signin page, just send all users to the dashboard
|
||||
# redirect_to = request.query_params.get('redirect_to')
|
||||
# if redirect_to and redirect_to.startswith('/'):
|
||||
# response = RedirectResponse(url=f"{APP_URL}{redirect_to}")
|
||||
# else:
|
||||
# response = RedirectResponse(url=DASHBOARD_URL)
|
||||
|
||||
response = RedirectResponse(url=DASHBOARD_URL)
|
||||
return _create_session_for_response(response, access_token)
|
||||
|
||||
|
||||
# TODO annotate response type
|
||||
@public_route
|
||||
async def auth_session(request: Request) -> JSONResponse:
|
||||
"""
|
||||
Receives the auth payload from the callback, validates it, creates a session,
|
||||
and returns a response with a cookie referencing the session.
|
||||
"""
|
||||
print("auth_session: Processing request")
|
||||
|
||||
# we just pass the hash params directly into the body of the request
|
||||
# so these are URL-encoded
|
||||
body = await request.body()
|
||||
print(f"auth_session: Raw body length: {len(body)}")
|
||||
|
||||
params = urllib.parse.parse_qs(body.decode('utf-8'))
|
||||
print(f"auth_session: Parsed params keys: {list(params.keys())}")
|
||||
|
||||
access_token = params.get('access_token', [None])[0]
|
||||
|
||||
if not access_token:
|
||||
print("auth_session: ERROR - No access_token in request body")
|
||||
raise AuthException("Invalid parameters passed to callback URL.")
|
||||
|
||||
print("auth_session: Found access_token, attempting to decode JWT")
|
||||
|
||||
try:
|
||||
# Decode the JWT to see what user info we have
|
||||
user_data = _decode_supabase_jwt(access_token)
|
||||
print(f"auth_session: Decoded JWT for user {user_data.sub} with email {user_data.email}")
|
||||
|
||||
# Check if this is an invite acceptance (look for invited_to_org in metadata)
|
||||
invited_to_org = None
|
||||
if user_data.user_metadata and 'invited_to_org' in user_data.user_metadata:
|
||||
invited_to_org = user_data.user_metadata.get('invited_to_org')
|
||||
print(f"auth_session: User is accepting invite to org {invited_to_org}")
|
||||
except Exception as e:
|
||||
print(f"auth_session: ERROR - Failed to decode JWT: {str(e)}")
|
||||
raise AuthException("Failed to decode access token")
|
||||
|
||||
content = StatusResponse(message="User authenticated successfully.")
|
||||
response = JSONResponse(content=content.model_dump())
|
||||
|
||||
print("auth_session: Creating session and setting cookie")
|
||||
result = _create_session_for_response(response, access_token)
|
||||
print("auth_session: Session created successfully, returning response")
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# TODO annotate response type
|
||||
@public_route
|
||||
async def auth_login(request: Request, body: LoginSchema) -> JSONResponse:
|
||||
"""
|
||||
Handle username/password logins.
|
||||
"""
|
||||
supabase = get_supabase()
|
||||
# returns `AuthResponse` (.venv/lib/python3.12/site-packages/gotrue/types.py:95)
|
||||
try:
|
||||
auth_response = supabase.auth.sign_in_with_password(
|
||||
{
|
||||
'email': body.email,
|
||||
'password': body.password,
|
||||
}
|
||||
)
|
||||
except gotrue.errors.AuthApiError as e:
|
||||
raise AuthException.from_gotrue_autherror(e)
|
||||
|
||||
if hasattr(auth_response, 'error'):
|
||||
raise AuthException()
|
||||
|
||||
access_token = auth_response.session.access_token
|
||||
content = StatusResponse(message="User authenticated successfully.")
|
||||
response = JSONResponse(content=content.model_dump())
|
||||
return _create_session_for_response(response, access_token)
|
||||
|
||||
|
||||
@public_route
|
||||
async def auth_otp(request: Request, body: OTPSchema) -> StatusResponse:
|
||||
"""
|
||||
Initiates the login flow by sending a one-time password (OTP) to the user's email.
|
||||
"""
|
||||
supabase = get_supabase()
|
||||
try:
|
||||
auth_response = supabase.auth.sign_in_with_otp(
|
||||
{
|
||||
'email': body.email,
|
||||
'options': {
|
||||
# set this to false if you do not want the user to be automatically signed up
|
||||
'should_create_user': False,
|
||||
'email_redirect_to': f"{APP_URL}/auth/callback",
|
||||
},
|
||||
}
|
||||
)
|
||||
except gotrue.errors.AuthApiError as e:
|
||||
raise AuthException.from_gotrue_autherror(e)
|
||||
|
||||
if hasattr(auth_response, 'error'):
|
||||
raise AuthException("Failed to send OTP.")
|
||||
|
||||
return StatusResponse(message="Please check your email.")
|
||||
|
||||
|
||||
@public_route
|
||||
async def auth_oauth(request: Request, body: OAuthSchema) -> RedirectMessageResponse:
|
||||
"""
|
||||
Redirects the user to the OAuth provider for authentication.
|
||||
"""
|
||||
supabase = get_supabase()
|
||||
provider = body.provider
|
||||
redirect_url = f"{API_URL}{reverse_path('auth_code')}"
|
||||
|
||||
if provider not in OAUTH_SCOPES:
|
||||
raise AuthException(f"Unsupported OAuth provider: {provider}")
|
||||
|
||||
# TODO re-enable this once invalid redirect destinations have been fixed in `auth_code`
|
||||
# if body.redirect_to:
|
||||
# params = urllib.parse.urlencode({"redirect_to": body.redirect_to})
|
||||
# redirect_url += f"?redirect_to={params}"
|
||||
|
||||
try:
|
||||
auth_response = supabase.auth.sign_in_with_oauth(
|
||||
{
|
||||
'provider': provider,
|
||||
'options': {
|
||||
'redirect_to': redirect_url,
|
||||
'scopes': OAUTH_SCOPES[provider],
|
||||
},
|
||||
}
|
||||
)
|
||||
except gotrue.errors.AuthApiError as e:
|
||||
raise AuthException.from_gotrue_autherror(e)
|
||||
|
||||
if hasattr(auth_response, 'error'):
|
||||
raise AuthException("Failed to initiate OAuth flow.")
|
||||
|
||||
return RedirectMessageResponse(
|
||||
message="Redirecting to OAuth provider...",
|
||||
url=auth_response.url,
|
||||
)
|
||||
|
||||
|
||||
@public_route
|
||||
async def auth_signup(request: Request, body: SignupSchema) -> StatusResponse:
|
||||
"""
|
||||
Handles user signup by creating a new user with the provided email and password.
|
||||
"""
|
||||
supabase = get_supabase()
|
||||
|
||||
try:
|
||||
auth_response = supabase.auth.sign_up(
|
||||
{
|
||||
'email': body.email,
|
||||
'password': body.password,
|
||||
'options': {
|
||||
'data': {
|
||||
'full_name': body.full_name,
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
except gotrue.errors.AuthApiError as e:
|
||||
raise AuthException.from_gotrue_autherror(e)
|
||||
|
||||
if hasattr(auth_response, 'error'):
|
||||
raise AuthException("Failed to sign up user.")
|
||||
|
||||
return StatusResponse(message="User signed up successfully.")
|
||||
|
||||
|
||||
@public_route
|
||||
async def auth_password_reset(request: Request, body: PasswordResetSchema) -> StatusResponse:
|
||||
"""
|
||||
Initiates a password reset flow by sending a reset email to the user.
|
||||
"""
|
||||
supabase = get_supabase()
|
||||
|
||||
try:
|
||||
# Use the frontend callback URL, same as the invite flow
|
||||
redirect_url = f"{APP_URL}/auth/callback"
|
||||
auth_response = supabase.auth.reset_password_for_email(body.email, {"redirect_to": redirect_url})
|
||||
except gotrue.errors.AuthApiError as e:
|
||||
raise AuthException.from_gotrue_autherror(e)
|
||||
|
||||
if hasattr(auth_response, 'error'):
|
||||
raise AuthException("Failed to send password reset email.")
|
||||
|
||||
return StatusResponse(message="Password reset email sent successfully.")
|
||||
|
||||
|
||||
async def auth_logout(request: Request) -> StatusResponse:
|
||||
"""
|
||||
Signs the user out by clearing the session cookie and expiring the session.
|
||||
"""
|
||||
content = StatusResponse(message="User logged out successfully.")
|
||||
response = JSONResponse(content=content.model_dump())
|
||||
|
||||
response.delete_cookie(key=AUTH_COOKIE_NAME, domain=_get_api_domain(), path="/")
|
||||
request.state.session.expire()
|
||||
|
||||
return response
|
||||
@@ -0,0 +1,171 @@
|
||||
from agentops.api.log_config import logger
|
||||
from .environment import (
|
||||
REDIS_HOST,
|
||||
REDIS_PORT,
|
||||
REDIS_USER,
|
||||
REDIS_PASSWORD,
|
||||
)
|
||||
|
||||
|
||||
if REDIS_HOST and REDIS_PORT:
|
||||
from redis import Redis
|
||||
|
||||
logger.info("Using Redis cache for production.")
|
||||
|
||||
_redis_creds = {
|
||||
'host': REDIS_HOST,
|
||||
'port': REDIS_PORT,
|
||||
'decode_responses': True,
|
||||
}
|
||||
if REDIS_USER and REDIS_PASSWORD:
|
||||
_redis_creds['username'] = REDIS_USER
|
||||
_redis_creds['password'] = REDIS_PASSWORD
|
||||
|
||||
_backend = Redis(**_redis_creds)
|
||||
|
||||
else:
|
||||
import os
|
||||
import sqlite3
|
||||
from collections import defaultdict
|
||||
import time
|
||||
|
||||
class BaseDevCache:
|
||||
"""
|
||||
Base class for local development cache.
|
||||
|
||||
Includes noops for methods we don't need in local development.
|
||||
"""
|
||||
|
||||
def zadd(self, key: str, mapping: dict) -> None:
|
||||
logger.warning("[agentops.common.cache] zadd() is not implemented in development")
|
||||
|
||||
def zremrangebyscore(self, key: str, min: int, max: int) -> None:
|
||||
logger.warning("[agentops.common.cache] zremrangebyscore() is not implemented in development")
|
||||
|
||||
def zcount(self, key: str, min: int, max: int) -> int:
|
||||
logger.warning("[agentops.common.cache] zcount() is not implemented in development")
|
||||
return 0
|
||||
|
||||
class SimpleCache(BaseDevCache):
|
||||
"""In-memory cache for local development."""
|
||||
|
||||
def __init__(self):
|
||||
self.store = defaultdict(lambda: None)
|
||||
self.expiry = {}
|
||||
|
||||
def get(self, key: str) -> str | None:
|
||||
if key in self.expiry and time.time() > self.expiry[key]:
|
||||
del self.store[key]
|
||||
del self.expiry[key]
|
||||
return None
|
||||
return self.store[key]
|
||||
|
||||
def setex(self, key: str, expiry: int, value: str) -> None:
|
||||
self.store[key] = value
|
||||
self.expiry[key] = time.time() + expiry
|
||||
|
||||
def expire(self, key: str, expiry: int) -> None:
|
||||
if key in self.store:
|
||||
self.expiry[key] = time.time() + expiry
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
if key in self.store:
|
||||
del self.store[key]
|
||||
if key in self.expiry:
|
||||
del self.expiry[key]
|
||||
|
||||
class SQLiteCache(BaseDevCache):
|
||||
"""SQLite-backed cache for local development."""
|
||||
|
||||
def __init__(self):
|
||||
self.db_path = os.path.join(os.getcwd(), "cache.db")
|
||||
self.conn = sqlite3.connect(self.db_path)
|
||||
self.conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS cache (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT,
|
||||
expiry INTEGER
|
||||
)
|
||||
""")
|
||||
self.conn.commit()
|
||||
|
||||
def get(self, key: str) -> str | None:
|
||||
cursor = self.conn.execute("SELECT value, expiry FROM cache WHERE key = ?", (key,))
|
||||
row = cursor.fetchone()
|
||||
if row:
|
||||
value, expiry = row
|
||||
if expiry is not None and time.time() > expiry:
|
||||
self.delete(key)
|
||||
return None
|
||||
return value
|
||||
return None
|
||||
|
||||
def setex(self, key: str, expiry: int, value: str) -> None:
|
||||
expiry_time = int(time.time() + expiry)
|
||||
self.conn.execute(
|
||||
"""
|
||||
INSERT OR REPLACE INTO cache (key, value, expiry)
|
||||
VALUES (?, ?, ?)
|
||||
""",
|
||||
(key, value, expiry_time),
|
||||
)
|
||||
self.conn.commit()
|
||||
|
||||
def expire(self, key: str, expiry: int) -> None:
|
||||
expiry_time = int(time.time() + expiry)
|
||||
self.conn.execute(
|
||||
"""
|
||||
UPDATE cache SET expiry = ? WHERE key = ?
|
||||
""",
|
||||
(expiry_time, key),
|
||||
)
|
||||
self.conn.commit()
|
||||
|
||||
def delete(self, key: str) -> None:
|
||||
self.conn.execute("DELETE FROM cache WHERE key = ?", (key,))
|
||||
self.conn.commit()
|
||||
|
||||
if os.path.exists("/.dockerenv"):
|
||||
logger.info("Using in-memory cache for local development.")
|
||||
_backend = SimpleCache()
|
||||
elif os.environ.get('GITHUB_ACTIONS') == 'true':
|
||||
logger.info("Using in-memory cache for GitHub Actions.")
|
||||
_backend = SimpleCache()
|
||||
else:
|
||||
logger.info("Using SQLite cache for local development.")
|
||||
_backend = SQLiteCache()
|
||||
|
||||
|
||||
def get(key: str) -> str | None:
|
||||
"""Get a value from the cache by key."""
|
||||
return _backend.get(key)
|
||||
|
||||
|
||||
def setex(key: str, expiry: int, value: str) -> None:
|
||||
"""Set a value in the cache with an expiry time."""
|
||||
_backend.setex(key, expiry, value)
|
||||
|
||||
|
||||
def expire(key: str, expiry: int) -> None:
|
||||
"""Set the expiry time for a key in the cache."""
|
||||
_backend.expire(key, expiry)
|
||||
|
||||
|
||||
def delete(key: str) -> None:
|
||||
"""Delete a key from the cache."""
|
||||
_backend.delete(key)
|
||||
|
||||
|
||||
def zadd(key: str, mapping: dict) -> None:
|
||||
"""Add elements to a sorted set."""
|
||||
_backend.zadd(key, mapping)
|
||||
|
||||
|
||||
def zremrangebyscore(key: str, min: int, max: int) -> None:
|
||||
"""Remove elements from a sorted set by score."""
|
||||
_backend.zremrangebyscore(key, min, max)
|
||||
|
||||
|
||||
def zcount(key: str, min: int, max: int) -> int:
|
||||
"""Count elements in a sorted set by score."""
|
||||
return _backend.zcount(key, min, max)
|
||||
@@ -0,0 +1,98 @@
|
||||
import os
|
||||
|
||||
# Base URLs and domains
|
||||
APP_DOMAIN = os.getenv("APP_DOMAIN", "app.agentops.ai")
|
||||
API_DOMAIN = os.getenv("API_DOMAIN", "api.agentops.ai")
|
||||
|
||||
# Protocol - defaults to https but can be overridden for local development
|
||||
PROTOCOL = os.getenv("PROTOCOL", "https")
|
||||
|
||||
# Full base URLs
|
||||
APP_URL = f"{PROTOCOL}://{APP_DOMAIN}"
|
||||
API_URL = f"{PROTOCOL}://{API_DOMAIN}"
|
||||
|
||||
# Common application URLs
|
||||
DASHBOARD_URL = f"{APP_URL}/projects"
|
||||
LOGIN_URL = f"{APP_URL}/login"
|
||||
|
||||
# CORS Configuration
|
||||
ALLOWED_ORIGINS = [
|
||||
APP_URL,
|
||||
]
|
||||
|
||||
|
||||
SQLALCHEMY_LOG_LEVEL = os.environ.get("SQLALCHEMY_LOG_LEVEL")
|
||||
|
||||
|
||||
SUPABASE_URL = os.getenv("SUPABASE_URL")
|
||||
SUPABASE_KEY = os.getenv("SUPABASE_KEY")
|
||||
|
||||
# Supabase Postgres connection details
|
||||
SUPABASE_HOST = os.getenv('SUPABASE_HOST')
|
||||
SUPABASE_PORT = os.getenv('SUPABASE_PORT')
|
||||
SUPABASE_DATABASE = os.getenv('SUPABASE_DATABASE')
|
||||
SUPABASE_USER = os.getenv('SUPABASE_USER')
|
||||
SUPABASE_PASSWORD = os.getenv('SUPABASE_PASSWORD')
|
||||
SUPABASE_SSLMODE = os.getenv('SUPABASE_SSLMODE', 'prefer')
|
||||
|
||||
# Supabase allows up to 20 pool connections and 1000 max connections.
|
||||
# Since we share connections with other instances (dev, staging) these defaults
|
||||
# are kept low and are expected to be overridden in production.
|
||||
# pool sizes are referenced *both* for the direct psycopg connection pool and
|
||||
# the SQLAlchemy connection pool (so in practice they are doubled)
|
||||
SUPABASE_MIN_POOL_SIZE: int = int(os.getenv('SUPABASE_MIN_POOL_SIZE', 1))
|
||||
SUPABASE_MAX_POOL_SIZE: int = int(os.getenv('SUPABASE_MAX_POOL_SIZE', 10))
|
||||
|
||||
# you can see the max pool size with (observed to be 240):
|
||||
# SELECT name, setting
|
||||
# FROM pg_settings
|
||||
# WHERE name IN ('max_connections', 'superuser_reserved_connections');
|
||||
|
||||
# you can see active connections with:
|
||||
# SELECT count(*) AS total, state, usename, backend_type
|
||||
# FROM pg_stat_activity
|
||||
# GROUP BY state, usename, backend_type;
|
||||
|
||||
|
||||
REDIS_HOST = os.getenv('REDIS_HOST')
|
||||
REDIS_PORT = os.getenv('REDIS_PORT')
|
||||
REDIS_USER = os.getenv('REDIS_USER')
|
||||
REDIS_PASSWORD = os.getenv('REDIS_PASSWORD')
|
||||
|
||||
|
||||
# enable rate limiting on public endpoints (default: false)
|
||||
RATE_LIMIT_ENABLE: bool = os.getenv("RATE_LIMIT_ENABLE", "false").lower() == "true"
|
||||
# Window time for counting rate limited requests
|
||||
RATE_LIMIT_WINDOW: int = int(os.getenv("RATE_LIMIT_WINDOW", 60)) # 60 seconds (1 minute)
|
||||
# Maximum allowed requests within the window
|
||||
RATE_LIMIT_COUNT: int = int(os.getenv("RATE_LIMIT_COUNT", 6)) # 6 requests per minute
|
||||
# How long to keep the rate limit key in cache after exceeding limits
|
||||
RATE_LIMIT_EXPIRY: int = int(os.getenv("RATE_LIMIT_EXPIRY", 60 * 60)) # 1 hour
|
||||
|
||||
|
||||
# number of users to allow for free users
|
||||
FREEPLAN_MAX_USERS: int = int(os.getenv('FREEPLAN_MAX_USERS', 1))
|
||||
# # number or orgs to allow for free users
|
||||
# TODO since freeplan is at the org level do we only allow a user to belong to one org?
|
||||
# FREEPLAN_MAX_ORGS = int(os.getenv('FREEPLAN_MAX_ORGS', 1))
|
||||
# number of projects to allow for free users
|
||||
FREEPLAN_MAX_PROJECTS: int = int(os.getenv('FREEPLAN_MAX_PROJECTS', 1))
|
||||
|
||||
# number of days we allow access to metrics data for free users
|
||||
FREEPLAN_METRICS_DAYS_CUTOFF: int = int(os.getenv('FREEPLAN_METRICS_DAYS_CUTOFF', 30))
|
||||
|
||||
# number of days to allow access to traces for free users
|
||||
FREEPLAN_TRACE_DAYS_CUTOFF: int = int(os.getenv('FREEPLAN_TRACE_DAYS_CUTOFF', 3))
|
||||
# minimum number of traces to include in a trace view
|
||||
FREEPLAN_TRACE_MIN_NUM: int = int(os.getenv('FREEPLAN_TRACE_MIN_NUM', 3))
|
||||
# number of spans to include the full contents of in a trace detail view
|
||||
FREEPLAN_SPANS_LIST_LIMIT: int = int(os.getenv('FREEPLAN_SPANS_LIST_LIMIT', 30))
|
||||
|
||||
# number of lines to show in the logs for free users
|
||||
FREEPLAN_LOGS_LINE_LIMIT: int = int(os.getenv('FREEPLAN_LOGS_LINE_LIMIT', 100))
|
||||
|
||||
# TODO 10,000 spans per month is not enforced.
|
||||
|
||||
# GitHub Oauth
|
||||
GITHUB_CLIENT_ID = os.environ.get("GITHUB_OAUTH_CLIENT_ID")
|
||||
GITHUB_CLIENT_SECRET = os.environ.get("GITHUB_OAUTH_CLIENT_SECRET")
|
||||
@@ -0,0 +1,202 @@
|
||||
from typing import Any
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import pydantic
|
||||
|
||||
|
||||
# Free:
|
||||
# 30 spans in waterfall
|
||||
# 100 lines of logs
|
||||
# one project
|
||||
# one seat
|
||||
# one org
|
||||
# metrics up to one month lookback
|
||||
# 5,000 spans per month
|
||||
# cant view traces older than 3 days other than last 3 traces regardless how old
|
||||
# Pro:
|
||||
# 100,000 spans per month included
|
||||
# tool costs
|
||||
# evals
|
||||
# notifications
|
||||
# exports
|
||||
# custom attributes
|
||||
# cost breakdowns by model
|
||||
# enterprise:
|
||||
# whateva you want babyy
|
||||
|
||||
|
||||
def freeplan_clamp_datetime(dt: None | datetime, days: int) -> datetime:
|
||||
"""
|
||||
Clamp a datetime object to a maximum number of days in the past for free plan users.
|
||||
|
||||
If the provided datetime is older than the cutoff date (further in the past),
|
||||
returns the cutoff date. Otherwise, returns the original datetime.
|
||||
"""
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(days=days)
|
||||
return max(dt, cutoff) if dt else cutoff
|
||||
|
||||
|
||||
def freeplan_clamp_start_time(start_time: None | datetime, days: int) -> tuple[datetime, bool]:
|
||||
"""
|
||||
Clamp a start_time datetime for freeplan users and return whether it was modified.
|
||||
|
||||
Args:
|
||||
start_time: The original start time (can be None)
|
||||
days: Number of days to allow in the past
|
||||
|
||||
Returns:
|
||||
tuple[datetime, bool]: (clamped_datetime, was_modified)
|
||||
- clamped_datetime: The final datetime to use
|
||||
- was_modified: True if the original value was changed for freeplan limits
|
||||
"""
|
||||
clamped = freeplan_clamp_datetime(start_time, days)
|
||||
return clamped, (start_time is None or clamped != start_time)
|
||||
|
||||
|
||||
def freeplan_clamp_end_time(end_time: None | datetime, days: int) -> tuple[datetime, bool]:
|
||||
"""
|
||||
Clamp an end_time datetime for freeplan users and return whether it was modified.
|
||||
|
||||
Args:
|
||||
end_time: The original end time (can be None)
|
||||
days: Number of days to allow in the past
|
||||
|
||||
Returns:
|
||||
tuple[datetime, bool]: (clamped_datetime, was_modified)
|
||||
- clamped_datetime: The final datetime to use
|
||||
- was_modified: True if the original value was changed for freeplan limits
|
||||
"""
|
||||
# If end_time is not provided, we start freeplan users at the current time
|
||||
actual_end_time = end_time if end_time is not None else datetime.now(timezone.utc)
|
||||
clamped = freeplan_clamp_datetime(actual_end_time, days)
|
||||
return clamped, (end_time is None or clamped != actual_end_time)
|
||||
|
||||
|
||||
class FreePlanFilteredResponse(pydantic.BaseModel):
|
||||
"""
|
||||
Base class for responses that need to be filtered for free plan users.
|
||||
|
||||
This class provides three mechanisms to control the data returned to free plan users:
|
||||
1. Exclude certain fields from the response (replacing them with empty values)
|
||||
2. Truncate list fields to a maximum number of items
|
||||
3. Truncate string fields to a maximum number of lines
|
||||
|
||||
When the `freeplan_truncated` flag is set to True, the `model_dump` method will apply
|
||||
these restrictions to the response.
|
||||
|
||||
Attributes:
|
||||
_freeplan_exclude (tuple[str]): A tuple of field names to be excluded from the response.
|
||||
_freeplan_maxitems (dict[str, int]): A dictionary mapping field names to the maximum
|
||||
number of items allowed in that list field.
|
||||
_freeplan_maxlines (dict[str, int]): A dictionary mapping field names to the maximum
|
||||
number of lines allowed in that string field.
|
||||
freeplan_truncated (bool): A flag to indicate whether the response should be restricted
|
||||
for free plan users.
|
||||
|
||||
Example for field exclusion:
|
||||
|
||||
class MyResponse(FreePlanFilteredResponse):
|
||||
_freeplan_exclude = ('field1', 'field2')
|
||||
|
||||
field1: str
|
||||
field2: str
|
||||
field3: str
|
||||
|
||||
response = MyResponse(field1='value1', field2='value2', field3='value3')
|
||||
response.freeplan_truncated = True
|
||||
|
||||
print(response.model_dump()) # {'field3': 'value3', 'field1': '', 'field2': ''}
|
||||
|
||||
Example for item truncation:
|
||||
class MyResponse(FreePlanFilteredResponse):
|
||||
_freeplan_maxitems = {'list_field': 2}
|
||||
|
||||
list_field: list[str]
|
||||
|
||||
response = MyResponse(list_field=['item1', 'item2', 'item3', 'item4'])
|
||||
response.freeplan_truncated = True
|
||||
|
||||
print(response.model_dump()) # {'list_field': ['item1', 'item2']}
|
||||
|
||||
Example for line truncation:
|
||||
|
||||
class MyResponse(FreePlanFilteredResponse):
|
||||
_freeplan_maxlines = {'multiline_field': 3}
|
||||
|
||||
multiline_field: str
|
||||
|
||||
response = MyResponse(multiline_field='line1\\nline2\\nline3\\nline4\\nline5')
|
||||
response.freeplan_truncated = True
|
||||
|
||||
print(response.model_dump()) # {'multiline_field': 'line1\\nline2\\nline3'}
|
||||
"""
|
||||
|
||||
# fields to return empty values for in freeplans
|
||||
_freeplan_exclude: tuple[str] = ()
|
||||
# list fields to return truncated values for in freeplans (limit number of items)
|
||||
_freeplan_maxitems: dict[str, int] = {}
|
||||
# string fields to return truncated values for in freeplans (limit line length)
|
||||
_freeplan_maxlines: dict[str, int] = {}
|
||||
|
||||
freeplan_truncated: bool = False # flag to activate this filtering
|
||||
|
||||
def _freeplan_get_empty_fields(self) -> dict[str, Any]:
|
||||
"""Get the fields we're filtering as empty values of the expected type."""
|
||||
# we want to always adhere to the schema in the returned data, so we instantiate
|
||||
# the fields as empty values of the expected type
|
||||
fields = {}
|
||||
|
||||
for field in self._freeplan_exclude:
|
||||
field_type = self.__annotations__.get(field)
|
||||
fields[field] = field_type() if field_type else None
|
||||
|
||||
return fields
|
||||
|
||||
def model_dump(self, **kwargs):
|
||||
"""Override model_dump to exclude fields we don't allow with freeplan"""
|
||||
if not self.freeplan_truncated:
|
||||
# if the flag is not set, just call the default implementation
|
||||
return super().model_dump(**kwargs)
|
||||
|
||||
# by default pydantic doesn't call the model_dump method on nested models
|
||||
# so we need to do that manually here
|
||||
dump = {}
|
||||
exclude = kwargs.get('exclude', [])
|
||||
|
||||
def _is_model(obj: Any) -> bool:
|
||||
return isinstance(obj, pydantic.BaseModel)
|
||||
|
||||
def _dump_list(value: list) -> list:
|
||||
return [item.model_dump(**kwargs) if _is_model(item) else item for item in value]
|
||||
|
||||
def _apply_max_lines(value: str, max_lines: int) -> str:
|
||||
"""Apply max lines to a string value."""
|
||||
return "\n".join(value.splitlines()[:max_lines])
|
||||
|
||||
for field, value in self.__dict__.items():
|
||||
if field in exclude:
|
||||
continue # support default behavior of `exclude`
|
||||
|
||||
if field in self._freeplan_exclude:
|
||||
continue # save resources by not serializing skipped fields
|
||||
|
||||
if _is_model(value):
|
||||
dump[field] = value.model_dump(**kwargs)
|
||||
elif isinstance(value, list):
|
||||
dump[field] = _dump_list(value)
|
||||
else:
|
||||
dump[field] = value
|
||||
|
||||
if field in self._freeplan_maxitems:
|
||||
# restrict the field to a maximum number of items
|
||||
assert isinstance(dump[field], list), f"Field {field} must be a list to truncate item count"
|
||||
max_items: int = self._freeplan_maxitems[field]
|
||||
dump[field] = dump[field][:max_items]
|
||||
|
||||
if field in self._freeplan_maxlines:
|
||||
# restrict the field to a maximum number of lines
|
||||
assert isinstance(dump[field], str), f"Field {field} must be a string to truncate line count"
|
||||
max_lines: int = self._freeplan_maxlines[field]
|
||||
dump[field] = _apply_max_lines(dump[field], max_lines)
|
||||
|
||||
# overwrite the fields we don't allow with freeplan
|
||||
return {**dump, **self._freeplan_get_empty_fields()}
|
||||
@@ -0,0 +1,37 @@
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI
|
||||
import logging
|
||||
from .postgres import close_connection as close_postgres
|
||||
from ..api.db.clickhouse_client import close_clickhouse_clients
|
||||
from ..api.db.supabase_client import close_supabase_clients
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
"""Manage application lifecycle."""
|
||||
# Startup
|
||||
logger.info("Starting up AgentOps API...")
|
||||
|
||||
yield
|
||||
|
||||
logger.info("Shutting down AgentOps API...")
|
||||
|
||||
try:
|
||||
close_postgres()
|
||||
logger.info("PostgreSQL connections closed")
|
||||
except Exception as e:
|
||||
logger.error(f"Error closing PostgreSQL: {e}")
|
||||
|
||||
try:
|
||||
await close_clickhouse_clients()
|
||||
logger.info("ClickHouse connections closed")
|
||||
except Exception as e:
|
||||
logger.error(f"Error closing ClickHouse: {e}")
|
||||
|
||||
try:
|
||||
await close_supabase_clients()
|
||||
logger.info("Supabase clients closed")
|
||||
except Exception as e:
|
||||
logger.error(f"Error closing Supabase: {e}")
|
||||
@@ -0,0 +1,58 @@
|
||||
from fastapi import Request, Response
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from agentops.api.log_config import logger
|
||||
|
||||
|
||||
DEFAULT_CONTENT_TYPE = "application/json"
|
||||
|
||||
|
||||
class DefaultContentTypeMiddleware(BaseHTTPMiddleware):
|
||||
"""Middleware to set default Content-Type if not set by the view"""
|
||||
|
||||
async def dispatch(self, request: Request, call_next) -> Response:
|
||||
response = await call_next(request)
|
||||
|
||||
if "content-type" not in response.headers:
|
||||
response.headers["content-type"] = DEFAULT_CONTENT_TYPE
|
||||
|
||||
return response
|
||||
|
||||
|
||||
class CacheControlMiddleware(BaseHTTPMiddleware):
|
||||
"""Middleware to set cache control headers on responses"""
|
||||
|
||||
async def dispatch(self, request: Request, call_next) -> Response:
|
||||
response = await call_next(request)
|
||||
|
||||
if "cache-control" not in response.headers:
|
||||
response.headers["cache-control"] = "no-store, no-cache, must-revalidate, max-age=0"
|
||||
if "pragma" not in response.headers:
|
||||
response.headers["pragma"] = "no-cache"
|
||||
if "expires" not in response.headers:
|
||||
response.headers["expires"] = "0"
|
||||
|
||||
return response
|
||||
|
||||
|
||||
class ExceptionMiddleware(BaseHTTPMiddleware):
|
||||
"""Middleware to handle exceptions and return a JSON response"""
|
||||
|
||||
async def dispatch(self, request: Request, call_next) -> Response:
|
||||
"""
|
||||
Return a JSON response with a 500 status code if an unhandled exception occurs.
|
||||
|
||||
Intentionally exclude all information about the exception in the response.
|
||||
|
||||
Note that `HTTPException`s are handled by FastAPI and will not reach this point.
|
||||
"""
|
||||
try:
|
||||
response = await call_next(request)
|
||||
return response
|
||||
except Exception as e:
|
||||
logger.error(f"Exception: {e}", exc_info=True)
|
||||
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content={"error": "Internal Server Error"},
|
||||
)
|
||||
@@ -0,0 +1,95 @@
|
||||
"""
|
||||
OpenAPI Schema Utilities
|
||||
|
||||
Utilities for combining OpenAPI schemas from multiple FastAPI applications.
|
||||
"""
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.openapi.utils import get_openapi
|
||||
from typing import Dict
|
||||
|
||||
|
||||
def create_combined_openapi_fn(
|
||||
main_app: FastAPI,
|
||||
mounted_apps: Dict[str, FastAPI],
|
||||
title: str = "Combined API",
|
||||
version: str = "1.0.0",
|
||||
description: str = "Combined API Schema",
|
||||
):
|
||||
"""
|
||||
Create a function that combines OpenAPI schemas from multiple FastAPI apps.
|
||||
|
||||
Args:
|
||||
main_app: The main FastAPI application
|
||||
mounted_apps: Dictionary of mounted apps with their mount paths as keys
|
||||
title: Title for the combined OpenAPI schema
|
||||
version: Version string for the combined schema
|
||||
description: Description for the combined schema
|
||||
|
||||
Returns:
|
||||
A function that can be assigned to app.openapi
|
||||
"""
|
||||
|
||||
def custom_openapi():
|
||||
# Return cached schema if available
|
||||
if main_app.openapi_schema:
|
||||
return main_app.openapi_schema
|
||||
|
||||
# Get the OpenAPI schema for the main app
|
||||
openapi_schema = get_openapi(
|
||||
title=title,
|
||||
version=version,
|
||||
description=description,
|
||||
routes=main_app.routes,
|
||||
)
|
||||
|
||||
# Add paths from mounted apps with proper prefixes
|
||||
for mount_path, app in mounted_apps.items():
|
||||
# Skip apps mounted at root (these should be handled separately)
|
||||
if mount_path == "/":
|
||||
prefix = ""
|
||||
else:
|
||||
# Ensure mount_path starts with / and doesn't end with /
|
||||
mount_path = "/" + mount_path.strip("/")
|
||||
prefix = mount_path
|
||||
|
||||
# Get schema for the mounted app
|
||||
app_schema = get_openapi(
|
||||
title=f"{app.title}" if hasattr(app, 'title') else "API",
|
||||
version=version,
|
||||
routes=app.routes,
|
||||
)
|
||||
|
||||
# Add paths with appropriate prefix
|
||||
for path, path_item in app_schema.get("paths", {}).items():
|
||||
# Handle root paths specially (e.g., "/" becomes "/api/")
|
||||
if path == "/":
|
||||
path = ""
|
||||
# Add the path with the appropriate prefix
|
||||
openapi_schema["paths"][f"{prefix}{path}"] = path_item
|
||||
|
||||
# Merge components
|
||||
if "components" in app_schema and "schemas" in app_schema["components"]:
|
||||
if "components" not in openapi_schema:
|
||||
openapi_schema["components"] = {}
|
||||
if "schemas" not in openapi_schema["components"]:
|
||||
openapi_schema["components"]["schemas"] = {}
|
||||
|
||||
openapi_schema["components"]["schemas"].update(app_schema["components"]["schemas"])
|
||||
|
||||
# Merge security schemes if present
|
||||
if "components" in app_schema and "securitySchemes" in app_schema["components"]:
|
||||
if "components" not in openapi_schema:
|
||||
openapi_schema["components"] = {}
|
||||
if "securitySchemes" not in openapi_schema["components"]:
|
||||
openapi_schema["components"]["securitySchemes"] = {}
|
||||
|
||||
openapi_schema["components"]["securitySchemes"].update(
|
||||
app_schema["components"]["securitySchemes"]
|
||||
)
|
||||
|
||||
# Cache the schema
|
||||
main_app.openapi_schema = openapi_schema
|
||||
return main_app.openapi_schema
|
||||
|
||||
return custom_openapi
|
||||
@@ -0,0 +1,176 @@
|
||||
from typing import Optional, Callable, Generator
|
||||
import logging
|
||||
from functools import wraps
|
||||
from contextlib import contextmanager
|
||||
|
||||
from sqlalchemy import create_engine, Engine
|
||||
from sqlalchemy.orm import (
|
||||
sessionmaker,
|
||||
selectinload,
|
||||
joinedload,
|
||||
Session,
|
||||
DeclarativeBase,
|
||||
)
|
||||
from sqlalchemy.inspection import inspect
|
||||
from sqlalchemy.orm.state import LoaderCallableStatus
|
||||
|
||||
from agentops.common.environment import (
|
||||
API_DOMAIN,
|
||||
SQLALCHEMY_LOG_LEVEL,
|
||||
SUPABASE_MIN_POOL_SIZE,
|
||||
SUPABASE_MAX_POOL_SIZE,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"require_loaded",
|
||||
"get_orm_session",
|
||||
"session_scope",
|
||||
"selectinload",
|
||||
"joinedload",
|
||||
"Session",
|
||||
"BaseModel",
|
||||
]
|
||||
|
||||
|
||||
logging.getLogger("sqlalchemy.engine").setLevel(
|
||||
getattr(
|
||||
logging,
|
||||
str(SQLALCHEMY_LOG_LEVEL).upper(),
|
||||
logging.ERROR,
|
||||
)
|
||||
)
|
||||
|
||||
_engine: Optional[Engine] = None
|
||||
|
||||
|
||||
class BaseModel(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
def patch_relationship() -> None:
|
||||
"""
|
||||
Patch the SQLAlchemy relationship function to raise an error if the relationship
|
||||
is not loaded. This is useful for ensuring that relationships are always loaded
|
||||
when accessed, preventing lazy loading in production code.
|
||||
"""
|
||||
import sqlalchemy.orm as orm
|
||||
|
||||
_orig_relationship = orm.relationship
|
||||
|
||||
def raise_lazy_relationships(*args, **kwargs):
|
||||
"""
|
||||
Override the default behavior of SQLAlchemy's relationship to raise an error
|
||||
if the relationship is not loaded. This is useful for ensuring that
|
||||
relationships are always loaded when accessed, preventing lazy loading
|
||||
in production code.
|
||||
"""
|
||||
kwargs.setdefault("lazy", "raise")
|
||||
return _orig_relationship(*args, **kwargs)
|
||||
|
||||
orm.relationship = raise_lazy_relationships
|
||||
|
||||
|
||||
if 'localhost' in API_DOMAIN:
|
||||
# If running locally, patch `orm.relationship` to raise an error if not loaded.
|
||||
patch_relationship()
|
||||
|
||||
|
||||
def require_loaded(*fields) -> Callable:
|
||||
"""
|
||||
Decorator that requires that the specified fields are loaded before calling the
|
||||
decorated function.
|
||||
|
||||
This is useful for ensuring that relationships are loaded before accessing them,
|
||||
since we can encounter false negatives/positives and do not ever want to run
|
||||
lazy loading in production code.
|
||||
|
||||
Usage:
|
||||
|
||||
class MyModel(BaseModel):
|
||||
related_field1 = relationship("RelatedModel1")
|
||||
related_field2 = relationship("RelatedModel2")
|
||||
|
||||
@require_loaded('related_field1', 'related_field2')
|
||||
def my_method(self):
|
||||
return self.related_field1, self.related_field2
|
||||
"""
|
||||
|
||||
def decorator(fn):
|
||||
@wraps(fn)
|
||||
def wrapper(self, *args, **kwargs):
|
||||
state = inspect(self)
|
||||
for field in fields:
|
||||
attr_state = state.attrs.get(field)
|
||||
try:
|
||||
assert attr_state is not None
|
||||
assert hasattr(attr_state, 'loaded_value')
|
||||
assert attr_state.loaded_value is not LoaderCallableStatus.NO_VALUE
|
||||
except AssertionError:
|
||||
raise RuntimeError(f"relationship '{field}' not loaded for {self.__class__.__name__}")
|
||||
|
||||
return fn(self, *args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def get_engine() -> Engine:
|
||||
"""
|
||||
Get the SQLAlchemy engine for the application.
|
||||
"""
|
||||
# import the ConnectionConfig late so that we ensure it has the correct values
|
||||
# in testing, for example, we patch this to update it with test values
|
||||
from .postgres import ConnectionConfig
|
||||
|
||||
global _engine
|
||||
|
||||
if _engine is None:
|
||||
# create an engine in parallel with the supabase postgres connection.
|
||||
# originally, I tried to utilize the existing pool, but it ended up being
|
||||
# very unreliable in longer running tasks. it's possible we can dig deeper
|
||||
# into the internals of psycopg_pool to make it work, but for now,
|
||||
# we create a new engine that uses the same connection string.
|
||||
_engine = create_engine(
|
||||
ConnectionConfig.to_connection_string(protocol="postgresql+psycopg"),
|
||||
pool_size=SUPABASE_MIN_POOL_SIZE,
|
||||
max_overflow=SUPABASE_MAX_POOL_SIZE - SUPABASE_MIN_POOL_SIZE,
|
||||
pool_pre_ping=True, # Test connections before use
|
||||
pool_recycle=3600, # Recycle idle connections after 1 hour
|
||||
)
|
||||
|
||||
return _engine
|
||||
|
||||
|
||||
def _create_session() -> Session:
|
||||
"""Internal function to create a new SQLAlchemy session."""
|
||||
return sessionmaker(bind=get_engine(), expire_on_commit=False)()
|
||||
|
||||
|
||||
def get_orm_session() -> Generator[Session, None, None]:
|
||||
"""
|
||||
Create a new SQLAlchemy ORM session.
|
||||
When used with FastAPI's Depends(), it will automatically close the session.
|
||||
Example: `orm: Session = Depends(get_orm_session)`
|
||||
"""
|
||||
session = _create_session()
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def session_scope() -> Generator[Session, None, None]:
|
||||
"""Provide a transactional scope around a series of operations."""
|
||||
session = _create_session()
|
||||
try:
|
||||
session.begin()
|
||||
yield session
|
||||
session.commit()
|
||||
except Exception:
|
||||
session.rollback()
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
@@ -0,0 +1,105 @@
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _is_array_index(key: str) -> bool:
|
||||
"""Check if a key represents an array index."""
|
||||
return key.isdigit()
|
||||
|
||||
|
||||
def _migrate_legacy_gen_ai_prompt(result: dict) -> None:
|
||||
"""Handle legacy OpenAI agents format migration in-place."""
|
||||
if 'gen_ai' in result and isinstance(result['gen_ai'], dict):
|
||||
if 'prompt' in result['gen_ai'] and isinstance(result['gen_ai']['prompt'], str):
|
||||
# Convert legacy format to indexed format
|
||||
legacy_prompt = result['gen_ai']['prompt']
|
||||
result['gen_ai']['prompt'] = [
|
||||
{
|
||||
'content': legacy_prompt,
|
||||
'role': 'user', # Default role for legacy data
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def otel_attributes_to_nested(attributes: dict[str, str]) -> dict[str, Any]:
|
||||
"""
|
||||
Convert OTEL attributes from a flat dictionary to a nested dictionary suitable
|
||||
for JSON serialization.
|
||||
|
||||
'foo.bar.0.baz': 'value' -> {'foo': {'bar': [{'baz': 'value'}]}}
|
||||
"""
|
||||
result = {}
|
||||
|
||||
for path, value in attributes.items():
|
||||
keys = path.split('.')
|
||||
current = result
|
||||
|
||||
# Navigate to the correct position
|
||||
for i, key in enumerate(keys[:-1]): # All keys except the last
|
||||
next_key = keys[i + 1]
|
||||
|
||||
# Skip if we hit a string value (can't traverse into it)
|
||||
if isinstance(current, str):
|
||||
break
|
||||
|
||||
if isinstance(current, list):
|
||||
# Current is a list, key must be numeric
|
||||
if not _is_array_index(key):
|
||||
break # Type mismatch: string key on list
|
||||
|
||||
key_int = int(key)
|
||||
# Extend list if needed
|
||||
while len(current) <= key_int:
|
||||
# Determine what to append based on next key
|
||||
if _is_array_index(next_key):
|
||||
current.append([])
|
||||
else:
|
||||
current.append({})
|
||||
current = current[key_int]
|
||||
|
||||
elif isinstance(current, dict):
|
||||
# Skip small numeric keys (0-9) on dicts as they likely indicate array indices
|
||||
if _is_array_index(key) and int(key) < 10:
|
||||
break # Type mismatch: numeric index on dict
|
||||
|
||||
if key not in current:
|
||||
# Create new structure based on next key
|
||||
if next_key == "0": # Specifically "0" suggests array start
|
||||
current[key] = []
|
||||
else:
|
||||
current[key] = {}
|
||||
|
||||
# Skip if the existing value is a string
|
||||
if isinstance(current[key], str):
|
||||
break
|
||||
|
||||
current = current[key]
|
||||
else:
|
||||
break # Unexpected type
|
||||
|
||||
else: # No break occurred, we can set the final value
|
||||
final_key = keys[-1]
|
||||
|
||||
# Skip if current is a string
|
||||
if isinstance(current, str):
|
||||
continue
|
||||
|
||||
if isinstance(current, list):
|
||||
# Current is a list, final key must be numeric
|
||||
if not _is_array_index(final_key):
|
||||
continue # Type mismatch
|
||||
|
||||
key_int = int(final_key)
|
||||
while len(current) <= key_int:
|
||||
current.append(None)
|
||||
current[key_int] = value
|
||||
|
||||
elif isinstance(current, dict):
|
||||
# Skip small numeric keys on dicts
|
||||
if _is_array_index(final_key) and int(final_key) < 10:
|
||||
continue # Type mismatch
|
||||
current[final_key] = value
|
||||
|
||||
# Apply legacy format migrations
|
||||
_migrate_legacy_gen_ai_prompt(result)
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,85 @@
|
||||
import atexit
|
||||
import signal
|
||||
import logging
|
||||
from psycopg_pool import ConnectionPool
|
||||
from .environment import (
|
||||
SUPABASE_HOST,
|
||||
SUPABASE_PORT,
|
||||
SUPABASE_DATABASE,
|
||||
SUPABASE_USER,
|
||||
SUPABASE_PASSWORD,
|
||||
SUPABASE_MIN_POOL_SIZE,
|
||||
SUPABASE_MAX_POOL_SIZE,
|
||||
SUPABASE_SSLMODE,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_supabase_pool: ConnectionPool | None = None
|
||||
|
||||
|
||||
class ConnectionConfig:
|
||||
"""
|
||||
Connection configuration for Supabase.
|
||||
|
||||
This is an intermediary because it allows us to easily modify the vars in tests.
|
||||
"""
|
||||
|
||||
host: str = SUPABASE_HOST
|
||||
port: str | int = SUPABASE_PORT
|
||||
database: str = SUPABASE_DATABASE
|
||||
user: str = SUPABASE_USER
|
||||
password: str = SUPABASE_PASSWORD
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Non-instantiable class has a lower chance of being printed."""
|
||||
raise NotImplementedError("Cannot instantiate ConnectionConfig.")
|
||||
|
||||
@classmethod
|
||||
def to_connection_string(cls, protocol: str = "postgresql") -> str:
|
||||
"""Format config as a URL connection string."""
|
||||
return f"{protocol}://{cls.user}:{cls.password}@{cls.host}:{cls.port}/{cls.database}?sslmode={SUPABASE_SSLMODE}"
|
||||
|
||||
|
||||
def _cleanup_handler(signum=None, frame=None):
|
||||
"""Universal cleanup handler for both signals and atexit."""
|
||||
logger.info(f"Cleanup handler called (signal: {signum})")
|
||||
close_connection()
|
||||
|
||||
|
||||
def get_connection(config: type[ConnectionConfig] = ConnectionConfig) -> ConnectionPool:
|
||||
"""
|
||||
Get the global Supabase Postgres connection pool.
|
||||
"""
|
||||
global _supabase_pool
|
||||
|
||||
if _supabase_pool is None:
|
||||
_supabase_pool = ConnectionPool(
|
||||
config.to_connection_string(),
|
||||
min_size=SUPABASE_MIN_POOL_SIZE,
|
||||
max_size=SUPABASE_MAX_POOL_SIZE,
|
||||
)
|
||||
|
||||
# Register cleanup handlers
|
||||
atexit.register(_cleanup_handler)
|
||||
signal.signal(signal.SIGTERM, _cleanup_handler)
|
||||
signal.signal(signal.SIGINT, _cleanup_handler)
|
||||
|
||||
logger.info(f"PostgreSQL pool created: min={SUPABASE_MIN_POOL_SIZE}, max={SUPABASE_MAX_POOL_SIZE}")
|
||||
|
||||
return _supabase_pool
|
||||
|
||||
|
||||
def close_connection() -> None:
|
||||
"""
|
||||
Close the global Supabase Postgres connection pool.
|
||||
"""
|
||||
global _supabase_pool
|
||||
|
||||
if _supabase_pool is not None:
|
||||
try:
|
||||
_supabase_pool.close()
|
||||
logger.info("PostgreSQL connection pool closed successfully")
|
||||
except Exception as e:
|
||||
logger.error(f"Error closing PostgreSQL pool: {e}")
|
||||
finally:
|
||||
_supabase_pool = None
|
||||
@@ -0,0 +1,66 @@
|
||||
import time
|
||||
|
||||
from . import cache
|
||||
from .environment import (
|
||||
RATE_LIMIT_ENABLE,
|
||||
RATE_LIMIT_WINDOW,
|
||||
RATE_LIMIT_COUNT,
|
||||
RATE_LIMIT_EXPIRY,
|
||||
)
|
||||
|
||||
WINDOW_US = RATE_LIMIT_WINDOW * 1_000_000 # convert to microseconds
|
||||
|
||||
|
||||
def _key(ip: str) -> str:
|
||||
"""Create a Redis key for the IP address."""
|
||||
return f"agentops.rate:{ip}"
|
||||
|
||||
|
||||
def _now_us() -> int:
|
||||
"""Get the current time in microseconds."""
|
||||
return int(time.time() * 1_000_000)
|
||||
|
||||
|
||||
def record_interaction(ip: str) -> None:
|
||||
"""
|
||||
Record an interaction from the given IP address.
|
||||
Uses a sliding window approach with sorted sets in Redis.
|
||||
"""
|
||||
key, now = _key(ip), _now_us()
|
||||
|
||||
cache.zremrangebyscore(key, 0, now - WINDOW_US)
|
||||
cache.zadd(key, {str(now): now})
|
||||
cache.expire(key, RATE_LIMIT_EXPIRY)
|
||||
|
||||
|
||||
def is_blocked(ip: str) -> bool:
|
||||
"""
|
||||
Check if the IP address is rate-limited.
|
||||
Returns True if the number of recent requests exceeds RATE_LIMIT_COUNT.
|
||||
Always returns False if RATE_LIMIT_ENABLE is False.
|
||||
"""
|
||||
if not RATE_LIMIT_ENABLE:
|
||||
return False
|
||||
|
||||
key, now = _key(ip), _now_us()
|
||||
|
||||
count = cache.zcount(key, now - WINDOW_US, now)
|
||||
return count > RATE_LIMIT_COUNT
|
||||
|
||||
|
||||
def clear(ip: str) -> None:
|
||||
"""
|
||||
Clear rate limit records for the given IP.
|
||||
This is primarily used for testing.
|
||||
"""
|
||||
key = _key(ip)
|
||||
cache.delete(key)
|
||||
|
||||
|
||||
def get_count(ip: str) -> int:
|
||||
"""
|
||||
Get the current count of requests for the given IP within the rate limit window.
|
||||
This is primarily used for testing.
|
||||
"""
|
||||
key, now = _key(ip), _now_us()
|
||||
return cache.zcount(key, now - WINDOW_US, now)
|
||||
@@ -0,0 +1,210 @@
|
||||
from typing import Any, Callable, Optional, Union, TypeVar
|
||||
from dataclasses import dataclass
|
||||
from fastapi import APIRouter, Request
|
||||
from abc import ABC, abstractmethod
|
||||
import inspect
|
||||
|
||||
|
||||
__all__ = ["RouteConfig", "BaseView", "register_routes", "reverse_path"]
|
||||
|
||||
_path_registry: dict[str, str] = {}
|
||||
|
||||
|
||||
class BaseView(ABC):
|
||||
"""
|
||||
Abstract base class for views in the route configuration.
|
||||
This class must be extended to create specific views.
|
||||
"""
|
||||
|
||||
request: Request
|
||||
|
||||
def __init__(self, request: Request):
|
||||
self.request = request
|
||||
|
||||
@classmethod
|
||||
async def create(cls, **kwargs) -> 'BaseView':
|
||||
"""
|
||||
This method is called when the view is instantiated.
|
||||
It can be overridden to perform any setup required for the view.
|
||||
"""
|
||||
return cls(**kwargs)
|
||||
|
||||
@abstractmethod
|
||||
async def __call__(self, *args, **kwargs):
|
||||
"""This method is called when the view is invoked."""
|
||||
...
|
||||
|
||||
|
||||
TBaseView = TypeVar('TBaseView', bound=BaseView)
|
||||
|
||||
|
||||
def _apply_view_docs(wrapper: Callable, view_class: type[TBaseView]) -> None:
|
||||
"""Applies documentation-related attributes to the wrapper function from a class based view."""
|
||||
call_method = getattr(view_class, '__call__')
|
||||
call_sig = inspect.signature(call_method)
|
||||
|
||||
params = []
|
||||
has_request_param = any(name == 'request' for name in call_sig.parameters.keys())
|
||||
|
||||
for name, param in call_sig.parameters.items():
|
||||
if name == 'self':
|
||||
# Only replace 'self' with 'request: Request' if there's no existing 'request' parameter
|
||||
if not has_request_param:
|
||||
param = inspect.Parameter(
|
||||
'request',
|
||||
inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
||||
annotation=Request,
|
||||
)
|
||||
else:
|
||||
# Skip 'self' parameter if there's already a 'request' parameter
|
||||
continue
|
||||
params.append(param)
|
||||
|
||||
wrapper.__doc__ = view_class.__doc__ # use the view class docstring
|
||||
wrapper.__name__ = view_class.__dict__.get('__name__', view_class.__name__)
|
||||
wrapper.__signature__ = inspect.Signature(
|
||||
parameters=params,
|
||||
return_annotation=call_sig.return_annotation,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class RouteConfig:
|
||||
"""
|
||||
Route configuration for a FastAPI route.
|
||||
|
||||
Usage with function endpoints:
|
||||
```python
|
||||
from fastapi import APIRouter
|
||||
from agentops.common.route_config import RouteConfig, register_routes
|
||||
|
||||
route_config: list[RouteConfig] = [
|
||||
RouteConfig(
|
||||
name="example_route",
|
||||
path="/example",
|
||||
endpoint=example_endpoint,
|
||||
methods=["GET"],
|
||||
),
|
||||
]
|
||||
router = APIRouter(prefix="/api")
|
||||
register_routes(router, route_config)
|
||||
|
||||
# use the router like you would normally
|
||||
app.include_router(router)
|
||||
|
||||
# this allows us to reverse paths by name
|
||||
from agentops.common.route_config import reverse_path
|
||||
path = reverse_path("example_route")
|
||||
>> "/api/example"
|
||||
```
|
||||
|
||||
Usage with class-based views:
|
||||
```python
|
||||
from agentops.common.route_config import BaseView, RouteConfig
|
||||
|
||||
class ExampleView(BaseView):
|
||||
__name__ = "Get Example Data"
|
||||
|
||||
async def __call__(self, item_id: int) -> dict:
|
||||
return {"id": item_id, "data": "example"}
|
||||
|
||||
route_config: list[RouteConfig] = [
|
||||
RouteConfig(
|
||||
name="example_view",
|
||||
path="/example/{item_id}",
|
||||
endpoint=ExampleView,
|
||||
methods=["GET"],
|
||||
),
|
||||
]
|
||||
```
|
||||
"""
|
||||
|
||||
name: str
|
||||
path: str
|
||||
endpoint: Union[Callable, type[TBaseView]]
|
||||
methods: list[str]
|
||||
summary: Optional[str] = None
|
||||
description: Optional[str] = None
|
||||
deprecated: Optional[bool] = None
|
||||
|
||||
@property
|
||||
def kwargs(self) -> dict[str, Any]:
|
||||
return {
|
||||
"summary": self.summary,
|
||||
"description": self.description,
|
||||
"deprecated": self.deprecated,
|
||||
}
|
||||
|
||||
def _create_class_view(self, view_class: type[TBaseView]) -> Callable:
|
||||
async def wrapper(request: Request, **kwargs):
|
||||
view_instance = await view_class.create(request=request)
|
||||
|
||||
# filter kwargs to only include parameters that the __call__ method expects
|
||||
call_method = getattr(view_instance, '__call__')
|
||||
sig = inspect.signature(call_method)
|
||||
filtered_kwargs = {}
|
||||
for param_name, param in sig.parameters.items():
|
||||
if param_name in kwargs:
|
||||
filtered_kwargs[param_name] = kwargs[param_name]
|
||||
|
||||
return await view_instance(**filtered_kwargs)
|
||||
|
||||
_apply_view_docs(wrapper, view_class)
|
||||
|
||||
# copy is_public attribute from class __call__ method to wrapper for AuthenticatedRoute middleware
|
||||
# TODO this is a bit too couple with agentops.auth for my taste, but we can fix that later.
|
||||
if hasattr(view_class.__call__, 'is_public'):
|
||||
wrapper.is_public = view_class.__call__.is_public
|
||||
|
||||
return wrapper
|
||||
|
||||
def as_view(self) -> Callable:
|
||||
"""
|
||||
Returns the appropriate callable for this route.
|
||||
If endpoint is a class-based view, wraps it with request injection.
|
||||
If endpoint is a function, returns it as-is.
|
||||
"""
|
||||
if not inspect.isclass(self.endpoint):
|
||||
return self.endpoint
|
||||
|
||||
if issubclass(self.endpoint, BaseView):
|
||||
return self._create_class_view(self.endpoint)
|
||||
|
||||
raise TypeError(f"`endpoint` {self.endpoint.__name__} must be a function or inherit from BaseView")
|
||||
|
||||
|
||||
def reverse_path(route_name: str) -> Optional[str]:
|
||||
"""
|
||||
Reverse a path by name.
|
||||
Args:
|
||||
route_name (str): The name of the route to reverse (from `RouteConfig.name`)
|
||||
"""
|
||||
global _path_registry
|
||||
|
||||
return _path_registry.get(route_name, None)
|
||||
|
||||
|
||||
def register_routes(router: APIRouter, configs: list[RouteConfig], prefix: str = "") -> None:
|
||||
"""
|
||||
Registers a list of route configurations with a FastAPI router, applying an optional prefix.
|
||||
|
||||
Args:
|
||||
router (APIRouter): The FastAPI router to register the routes with.
|
||||
configs (list[RouteConfig]): A list of RouteConfig objects defining the routes to register.
|
||||
prefix (str): An optional prefix to prepend to the route paths. This is in addition to
|
||||
any prefix already defined on the router itself and is used when adding an app
|
||||
to a parent app with `app.mount()` (since we are not able to determine the prefix
|
||||
of the parent app at runtime).
|
||||
"""
|
||||
global _path_registry
|
||||
|
||||
for config in configs:
|
||||
_path_registry[config.name] = f"{prefix}{router.prefix}{config.path}"
|
||||
|
||||
for method in config.methods:
|
||||
router.add_api_route(
|
||||
path=config.path,
|
||||
endpoint=config.as_view(),
|
||||
methods=[method],
|
||||
**config.kwargs,
|
||||
)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
Callback handler for sanitizing Sentry events.
|
||||
|
||||
This was created to address credential leaks from Supabase auth (gotrue) which
|
||||
uses `TypedDict` for all internal data structures, which can be printed out
|
||||
in variable extraction in Sentry events.
|
||||
|
||||
A long-term solution would require patching the types in the `gotrue` library
|
||||
to use a sanitizable type, but that is an extensive refactor.
|
||||
"""
|
||||
|
||||
from typing import Optional, Any
|
||||
|
||||
|
||||
SENSITIVE_DATA_PLACEHOLDER = "[REDACTED]"
|
||||
|
||||
# non-exhaustive list of vars to remove from Sentry events
|
||||
REMOVE_VARS = {
|
||||
"password",
|
||||
"secret",
|
||||
"token",
|
||||
"api_key",
|
||||
}
|
||||
|
||||
|
||||
def _sanitize_dictionaries(vars: dict) -> dict:
|
||||
"""
|
||||
Recursively remove sensitive content from the given dictionary of variables.
|
||||
"""
|
||||
for key in list(vars):
|
||||
if key.lower() in REMOVE_VARS:
|
||||
vars[key] = SENSITIVE_DATA_PLACEHOLDER
|
||||
elif isinstance(vars[key], dict):
|
||||
vars[key] = _sanitize_dictionaries(vars[key])
|
||||
elif isinstance(vars[key], list):
|
||||
# Create a new list to hold the sanitized items
|
||||
sanitized_list = []
|
||||
for i, item in enumerate(vars[key]):
|
||||
if isinstance(item, dict):
|
||||
sanitized_list.append(_sanitize_dictionaries(item))
|
||||
else:
|
||||
sanitized_list.append(item)
|
||||
vars[key] = sanitized_list
|
||||
return vars
|
||||
|
||||
|
||||
def sanitize_event(event: dict[str, Any], hint: dict[str, Any]) -> Optional[dict[str, Any]]:
|
||||
if 'exception' not in event:
|
||||
return event
|
||||
|
||||
for value in event["exception"].get("values", []):
|
||||
frames = value.get("stacktrace", {}).get("frames", [])
|
||||
for frame in frames:
|
||||
if frame_vars := frame.get("vars"):
|
||||
frame['vars'] = _sanitize_dictionaries(frame_vars)
|
||||
return event
|
||||
@@ -0,0 +1,9 @@
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class UsageType(str, Enum):
|
||||
"""Types of usage we track for billing"""
|
||||
|
||||
TOKENS = "tokens"
|
||||
SPANS = "spans"
|
||||
# Future: STORAGE = "storage", COMPUTE = "compute", etc.
|
||||
@@ -0,0 +1,47 @@
|
||||
import functools
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel
|
||||
from .environment import APP_URL
|
||||
|
||||
|
||||
def add_cors_headers(
|
||||
*,
|
||||
origins: list[str] | None = None,
|
||||
methods: list[str] | None = None,
|
||||
):
|
||||
"""
|
||||
Render a Pydantic object response as a JSON response with CORS headers.
|
||||
|
||||
Use this decorator when you need control over individual views that need to
|
||||
have CORS headers added to the response.
|
||||
|
||||
Arguments:
|
||||
origins: List of allowed origins for CORS. Defaults to the APP_URL.
|
||||
methods: List of allowed methods for CORS. Defaults to GET, OPTIONS.
|
||||
"""
|
||||
|
||||
if origins is None:
|
||||
origins = [APP_URL]
|
||||
|
||||
if methods is None:
|
||||
methods = ["GET", "OPTIONS"]
|
||||
|
||||
def decorator(func):
|
||||
@functools.wraps(func)
|
||||
async def wrapper(*args, **kwargs) -> JSONResponse:
|
||||
response_object: BaseModel = await func(*args, **kwargs)
|
||||
assert isinstance(response_object, BaseModel), "View must return a Pydantic model"
|
||||
|
||||
return JSONResponse(
|
||||
content=response_object.model_dump(),
|
||||
headers={
|
||||
"Access-Control-Allow-Origin": ', '.join(origins),
|
||||
"Access-Control-Allow-Credentials": "true",
|
||||
"Access-Control-Allow-Methods": ', '.join(methods),
|
||||
"Access-Control-Allow-Headers": "*",
|
||||
},
|
||||
)
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
@@ -0,0 +1,33 @@
|
||||
from fastapi import FastAPI, APIRouter
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from agentops.common.environment import ALLOWED_ORIGINS
|
||||
from agentops.common.middleware import (
|
||||
CacheControlMiddleware,
|
||||
DefaultContentTypeMiddleware,
|
||||
ExceptionMiddleware,
|
||||
)
|
||||
from agentops.common.route_config import register_routes
|
||||
from agentops.auth.middleware import AuthenticatedRoute
|
||||
|
||||
from .routes import route_config
|
||||
|
||||
__all__ = ["app"]
|
||||
|
||||
app = FastAPI(title="Deploy")
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=ALLOWED_ORIGINS,
|
||||
allow_credentials=True,
|
||||
allow_methods=["GET", "POST", "DELETE", "OPTIONS"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.add_middleware(DefaultContentTypeMiddleware)
|
||||
app.add_middleware(CacheControlMiddleware)
|
||||
app.add_middleware(ExceptionMiddleware)
|
||||
|
||||
router = APIRouter(route_class=AuthenticatedRoute)
|
||||
register_routes(router, route_config, prefix="/deploy")
|
||||
app.include_router(router)
|
||||
@@ -0,0 +1,99 @@
|
||||
from __future__ import annotations
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
import sqlalchemy.exc
|
||||
from sqlalchemy import orm
|
||||
from sqlalchemy.orm import joinedload, deferred
|
||||
import sqlalchemy as model
|
||||
from agentops.common.orm import BaseModel
|
||||
import jockey
|
||||
|
||||
|
||||
def normalize_uuid(id_: str | UUID) -> UUID:
|
||||
"""Normalize value to a UUID."""
|
||||
return UUID(id_) if isinstance(id_, str) else id_
|
||||
|
||||
|
||||
class HostingProjectModel(BaseModel):
|
||||
"""Model that maps to the deploy.projects table"""
|
||||
|
||||
__tablename__ = "projects"
|
||||
__table_args__ = {"schema": "deploy"}
|
||||
|
||||
id = model.Column(model.UUID, model.ForeignKey("public.projects.id"), primary_key=True)
|
||||
github_oath_access_token = model.Column(model.String, nullable=True)
|
||||
user_callback_url = model.Column(model.String, nullable=True)
|
||||
watch_path = model.Column(model.String, nullable=True)
|
||||
entrypoint = model.Column(model.String, nullable=True)
|
||||
git_branch = model.Column(model.String, nullable=True) # which branch to deploy (could be tag or hash)
|
||||
git_url = model.Column(model.String, nullable=True) # repo url
|
||||
# TODO remove `deferred` once migration has been applied.
|
||||
pack_name = deferred(model.Column(model.String, nullable=True, default=None))
|
||||
|
||||
project = orm.relationship("agentops.opsboard.models.ProjectModel")
|
||||
|
||||
@property
|
||||
def namespace(self) -> str:
|
||||
"""
|
||||
Get the Kubernetes namespace for this deployment.
|
||||
|
||||
Used to ensure isolation of resources between users.
|
||||
"""
|
||||
# Use project_id as namespace
|
||||
return str(self.id)
|
||||
|
||||
@property
|
||||
def app_name(self) -> str:
|
||||
"""
|
||||
Get the application name for this deployment.
|
||||
|
||||
Used to identify resources related to this deployment.
|
||||
TODO update the app_labels upstream to make this more explicit.
|
||||
"""
|
||||
return str(self.id)
|
||||
|
||||
@property
|
||||
def deployment_config(self) -> jockey.DeploymentConfig:
|
||||
"""Get the deployment configuration for this project."""
|
||||
# TODO we can simplify this after the migration runs
|
||||
try:
|
||||
pack_name = self.pack_name
|
||||
except sqlalchemy.exc.ProgrammingError:
|
||||
pack_name = None
|
||||
|
||||
return jockey.DeploymentConfig.from_pack(
|
||||
pack_name,
|
||||
namespace=self.namespace,
|
||||
project_id=self.id,
|
||||
github_access_token=self.github_oath_access_token,
|
||||
repository_url=self.git_url,
|
||||
branch=self.git_branch,
|
||||
entrypoint=self.entrypoint,
|
||||
watch_path=self.watch_path,
|
||||
agentops_api_key=str(self.project.api_key),
|
||||
callback_url=self.user_callback_url,
|
||||
secret_names=jockey.list_secrets(self.namespace, self.id),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_by_id(cls, session: orm.Session, project_id: str | UUID) -> Optional[HostingProjectModel]:
|
||||
"""Get a hosting project by ID with project and org relationships preloaded."""
|
||||
from agentops.opsboard.models import ProjectModel
|
||||
|
||||
return (
|
||||
session.query(cls)
|
||||
.filter(cls.id == normalize_uuid(project_id))
|
||||
.options(joinedload(cls.project).joinedload(ProjectModel.org))
|
||||
.first()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_or_create_by_id(cls, session: orm.Session, project_id: str | UUID) -> HostingProjectModel:
|
||||
"""Get or create a hosting project by ID."""
|
||||
|
||||
if not (instance := cls.get_by_id(session, project_id)):
|
||||
instance = cls(id=normalize_uuid(project_id))
|
||||
session.add(instance)
|
||||
session.commit()
|
||||
session.refresh(instance)
|
||||
return instance
|
||||
@@ -0,0 +1,135 @@
|
||||
from agentops.common.route_config import RouteConfig
|
||||
from agentops.deploy.views.setup import (
|
||||
GithubListReposView,
|
||||
GithubOAuthCallbackView,
|
||||
)
|
||||
from agentops.deploy.views.deploy import (
|
||||
CreateUpdateSecretView,
|
||||
ListSecretsView,
|
||||
DeleteSecretView,
|
||||
UpdateDeploymentView,
|
||||
InitiateBuildView,
|
||||
InitiateDeploymentView,
|
||||
InitiateRunView,
|
||||
DeploymentStatusView,
|
||||
DeploymentBuildLogView,
|
||||
DeploymentHistoryView,
|
||||
ListUserDeploymentsView,
|
||||
DeleteDeploymentView,
|
||||
)
|
||||
|
||||
|
||||
route_config: list[RouteConfig] = [
|
||||
RouteConfig(
|
||||
name='github_auth',
|
||||
path="/github/auth",
|
||||
endpoint=GithubOAuthCallbackView,
|
||||
methods=["GET"],
|
||||
summary="Github authorization callback",
|
||||
description="Exchange github auth code for access_token and store in new or updated deploy project",
|
||||
),
|
||||
RouteConfig(
|
||||
name='fetch_user_repos',
|
||||
path="/github/repos",
|
||||
endpoint=GithubListReposView,
|
||||
methods=["GET"],
|
||||
summary="List repositories user has access to",
|
||||
description="List the repositories the user has allowed the integration to have access to",
|
||||
),
|
||||
RouteConfig(
|
||||
name='create_update_secret',
|
||||
path="/deployments/{project_id}/secrets",
|
||||
endpoint=CreateUpdateSecretView,
|
||||
methods=["POST"],
|
||||
summary="Create or update a secret for a project",
|
||||
description="Create or update a secret key-value pair for a specific project deployment",
|
||||
),
|
||||
RouteConfig(
|
||||
name='list_secrets',
|
||||
path="/deployments/{project_id}/secrets",
|
||||
endpoint=ListSecretsView,
|
||||
methods=["GET"],
|
||||
summary="List secrets for a project",
|
||||
description="Get all secret names for a specific project deployment (values are not returned for security)",
|
||||
),
|
||||
RouteConfig(
|
||||
name='delete_secret',
|
||||
path="/deployments/{project_id}/secrets/{secret_name}",
|
||||
endpoint=DeleteSecretView,
|
||||
methods=["DELETE"],
|
||||
summary="Delete a secret for a project",
|
||||
description="Delete a specific secret key-value pair for a project deployment",
|
||||
),
|
||||
RouteConfig(
|
||||
name='initiate_build',
|
||||
path="/deployments/{project_id}/build",
|
||||
endpoint=InitiateBuildView,
|
||||
methods=["POST"],
|
||||
summary="Build image only",
|
||||
description="Build and push Docker image without creating deployment resources",
|
||||
),
|
||||
RouteConfig(
|
||||
name='initiate_deployment',
|
||||
path="/deployments/{project_id}/launch",
|
||||
endpoint=InitiateDeploymentView,
|
||||
methods=["POST"],
|
||||
summary="Initiate a project deployment",
|
||||
description="Start the deployment process for a specific project",
|
||||
),
|
||||
RouteConfig(
|
||||
name='initiate_run',
|
||||
path="/deployments/{project_id}/run",
|
||||
endpoint=InitiateRunView,
|
||||
methods=["POST"],
|
||||
summary="Run agent job",
|
||||
description="Build image and run as one-time job with input data",
|
||||
),
|
||||
RouteConfig(
|
||||
name='deployment_status',
|
||||
path="/deployments/{project_id}/jobs/{job_id}/status",
|
||||
endpoint=DeploymentStatusView,
|
||||
methods=["GET"],
|
||||
summary="Get deployment job status and events",
|
||||
description="Get the current status and event history for a specific deployment job",
|
||||
),
|
||||
RouteConfig(
|
||||
name='deployment_build_logs',
|
||||
path="/deployments/{project_id}/jobs/{job_id}/logs",
|
||||
endpoint=DeploymentBuildLogView,
|
||||
methods=["GET"],
|
||||
summary="Stream build logs from builder pod",
|
||||
description="Stream real-time build logs from the builder pod for a specific deployment job",
|
||||
),
|
||||
RouteConfig(
|
||||
name='deployment_history',
|
||||
path="/deployments/{project_id}/history",
|
||||
endpoint=DeploymentHistoryView,
|
||||
methods=["GET"],
|
||||
summary="Get project deployment history",
|
||||
description="Get all deployment jobs and their status for a project",
|
||||
),
|
||||
RouteConfig(
|
||||
name='update_deployment',
|
||||
path="/deployments/{project_id}",
|
||||
endpoint=UpdateDeploymentView,
|
||||
methods=["POST"],
|
||||
summary="Update deployment configuration",
|
||||
description="Update the deployment configuration for a specific project",
|
||||
),
|
||||
RouteConfig(
|
||||
name='update_deployment',
|
||||
path="/deployments",
|
||||
endpoint=ListUserDeploymentsView,
|
||||
methods=["GET"],
|
||||
summary="Get a list of all deployments (projects)",
|
||||
description="Get a list of all the projects a user has access ",
|
||||
),
|
||||
RouteConfig(
|
||||
name='delete_deployment',
|
||||
path="/deployments/{project_id}",
|
||||
endpoint=DeleteDeploymentView,
|
||||
methods=["DELETE"],
|
||||
summary="Delete a deployment",
|
||||
description="Delete a deployment and clean up associated resources for a specific project",
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,122 @@
|
||||
from typing import Optional, Any
|
||||
from enum import Enum
|
||||
from datetime import datetime
|
||||
import pydantic
|
||||
from agentops.opsboard.schemas import OrgSummaryResponse
|
||||
|
||||
|
||||
class StatusResponse(pydantic.BaseModel):
|
||||
success: bool
|
||||
message: str
|
||||
|
||||
|
||||
class DeploymentStatusResponse(StatusResponse):
|
||||
job_id: str
|
||||
|
||||
|
||||
class DeploymentEventSchema(pydantic.BaseModel):
|
||||
type: str
|
||||
status: str
|
||||
message: str
|
||||
timestamp: datetime
|
||||
|
||||
@pydantic.field_validator('timestamp', mode='before')
|
||||
def validate_timestamp(cls, value: datetime) -> str:
|
||||
if not isinstance(value, datetime):
|
||||
raise ValueError(f"`timestamp` must be a datetime, got {type(value)}")
|
||||
return value.isoformat()
|
||||
|
||||
@pydantic.field_validator('status', mode='before')
|
||||
def validate_status(cls, value: Enum) -> str:
|
||||
if not isinstance(value, Enum):
|
||||
raise ValueError(f"`status` must be an Enum, got {type(value)}")
|
||||
return value.value
|
||||
|
||||
|
||||
class DeploymentEventResponse(pydantic.BaseModel):
|
||||
events: list[DeploymentEventSchema] = pydantic.Field(default_factory=list)
|
||||
|
||||
|
||||
class DeploymentJobSchema(pydantic.BaseModel):
|
||||
id: str
|
||||
queued_at: str
|
||||
status: str
|
||||
message: str
|
||||
|
||||
|
||||
class DeploymentHistoryResponse(pydantic.BaseModel):
|
||||
jobs: list[DeploymentJobSchema] = pydantic.Field(default_factory=list)
|
||||
|
||||
|
||||
class SecretSchema(pydantic.BaseModel):
|
||||
name: str
|
||||
value: Optional[str] = None
|
||||
|
||||
|
||||
class CreateSecretRequest(pydantic.BaseModel):
|
||||
name: str
|
||||
value: str
|
||||
|
||||
|
||||
class UpdateDeploymentRequest(pydantic.BaseModel):
|
||||
github_oath_access_token: Optional[str] = None
|
||||
user_callback_url: Optional[str] = None
|
||||
watch_path: Optional[str] = None
|
||||
entrypoint: Optional[str] = None
|
||||
git_branch: Optional[str] = None
|
||||
git_url: Optional[str] = None
|
||||
|
||||
|
||||
class ListSecretsResponse(pydantic.BaseModel):
|
||||
secrets: list[SecretSchema] = pydantic.Field(default_factory=list)
|
||||
|
||||
|
||||
class RunJobRequest(pydantic.BaseModel):
|
||||
"""Request schema for running a job with input data."""
|
||||
|
||||
inputs: dict[str, Any] = pydantic.Field(
|
||||
description="Input data to pass to the agent",
|
||||
examples=[{"topic": "AI trends", "format": "summary"}],
|
||||
)
|
||||
callback_url: Optional[str] = pydantic.Field(
|
||||
description="Callback URL to receive run results. No callback URL will use the project default",
|
||||
examples=["https://your-callback-url.com"],
|
||||
default=None,
|
||||
)
|
||||
|
||||
|
||||
class HostingProjectResponse(pydantic.BaseModel):
|
||||
"""
|
||||
Combined response that includes both project and hosting project data.
|
||||
This matches the frontend IHostingProject interface.
|
||||
"""
|
||||
|
||||
# Project fields
|
||||
id: str
|
||||
name: str
|
||||
api_key: str
|
||||
org_id: str
|
||||
environment: str
|
||||
org: OrgSummaryResponse
|
||||
trace_count: int = 0
|
||||
|
||||
# Hosting project fields
|
||||
git_url: Optional[str] = None
|
||||
git_branch: Optional[str] = None
|
||||
entrypoint: Optional[str] = None
|
||||
watch_path: Optional[str] = None
|
||||
user_callback_url: Optional[str] = None
|
||||
github_oath_access_token: Optional[str] = None
|
||||
|
||||
@pydantic.field_validator("id", "api_key", "org_id", mode="before")
|
||||
@classmethod
|
||||
def validate_uuid(cls, v):
|
||||
from agentops.opsboard.schemas import uuid_to_str
|
||||
|
||||
return uuid_to_str(v)
|
||||
|
||||
@pydantic.field_validator("environment", mode="before")
|
||||
@classmethod
|
||||
def validate_environment_enum(cls, v):
|
||||
"""Convert the environment Enum to a string."""
|
||||
return v.value if isinstance(v, Enum) else v
|
||||
@@ -0,0 +1,433 @@
|
||||
from datetime import datetime
|
||||
import logging
|
||||
|
||||
from fastapi import Depends, HTTPException
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from jockey import (
|
||||
TaskType,
|
||||
BaseEvent,
|
||||
queue_task,
|
||||
get_task_status,
|
||||
get_task_events,
|
||||
get_tasks,
|
||||
create_secret,
|
||||
delete_secret,
|
||||
list_secrets,
|
||||
delete_deployment_resources,
|
||||
)
|
||||
from jockey.backend.models.image import Image
|
||||
|
||||
from agentops.common.orm import get_orm_session
|
||||
from agentops.common.route_config import BaseView
|
||||
from agentops.opsboard.models import ProjectModel
|
||||
from agentops.deploy.models import HostingProjectModel
|
||||
from agentops.deploy.schemas import (
|
||||
StatusResponse,
|
||||
HostingProjectResponse,
|
||||
UpdateDeploymentRequest,
|
||||
DeploymentJobSchema,
|
||||
RunJobRequest,
|
||||
DeploymentStatusResponse,
|
||||
DeploymentEventSchema,
|
||||
DeploymentEventResponse,
|
||||
DeploymentHistoryResponse,
|
||||
SecretSchema,
|
||||
CreateSecretRequest,
|
||||
ListSecretsResponse,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# project_id is the internal project ID that the deployment belongs to
|
||||
# it is the same on both the `ProjectModel` and `HostingProjectModel`
|
||||
# job_id is the ID generated by the deploy backend for the iteration of the deployment
|
||||
|
||||
|
||||
class BaseDeploymentView(BaseView):
|
||||
async def get_hosting_project(self, orm: Session, project_id: str) -> HostingProjectModel:
|
||||
# load project in a separate query because ProjectModel.get_by_id loads a
|
||||
# bunch of stuff we need for the auth check
|
||||
if not (project := ProjectModel.get_by_id(orm, project_id)):
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
if not project.org.is_user_member(self.request.state.session.user_id):
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
return HostingProjectModel.get_or_create_by_id(orm, project_id)
|
||||
|
||||
|
||||
class CreateUpdateSecretView(BaseDeploymentView):
|
||||
async def __call__(
|
||||
self,
|
||||
project_id: str,
|
||||
body: CreateSecretRequest,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> StatusResponse:
|
||||
"""
|
||||
Create or update a secret for a deployment.
|
||||
|
||||
This will be stored directly on the k8s cluster.
|
||||
"""
|
||||
project: HostingProjectModel = await self.get_hosting_project(orm, project_id)
|
||||
delete_secret(project.namespace, project.id, body.name)
|
||||
create_secret(project.namespace, project.id, body.name, body.value)
|
||||
|
||||
return StatusResponse(success=True, message="Successfully created secret")
|
||||
|
||||
|
||||
class ListSecretsView(BaseDeploymentView):
|
||||
async def __call__(
|
||||
self,
|
||||
project_id: str,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> ListSecretsResponse:
|
||||
"""
|
||||
List all secrets for a deployment
|
||||
|
||||
Currently, we just list the names of the keys and doesn't allow retrieval of values for security.
|
||||
"""
|
||||
project: HostingProjectModel = await self.get_hosting_project(orm, project_id)
|
||||
secret_names: list[str] = list_secrets(project.namespace, project.id)
|
||||
|
||||
return ListSecretsResponse(
|
||||
secrets=[SecretSchema(name=name) for name in secret_names],
|
||||
)
|
||||
|
||||
|
||||
class DeleteSecretView(BaseDeploymentView):
|
||||
async def __call__(
|
||||
self,
|
||||
project_id: str,
|
||||
secret_name: str,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> StatusResponse:
|
||||
"""
|
||||
Delete a secret for a deployment.
|
||||
|
||||
This will remove the secret from the k8s cluster.
|
||||
"""
|
||||
project: HostingProjectModel = await self.get_hosting_project(orm, project_id)
|
||||
delete_secret(project.namespace, project.id, secret_name)
|
||||
|
||||
return StatusResponse(success=True, message="Successfully deleted secret")
|
||||
|
||||
|
||||
class UpdateDeploymentView(BaseDeploymentView):
|
||||
async def __call__(
|
||||
self,
|
||||
project_id: str,
|
||||
body: UpdateDeploymentRequest,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> StatusResponse:
|
||||
"""
|
||||
Update deployment configuration for a project.
|
||||
|
||||
Updates the HostingProjectModel with the provided values.
|
||||
Only non-None values in the request will be updated.
|
||||
"""
|
||||
project: HostingProjectModel = await self.get_hosting_project(orm, project_id)
|
||||
|
||||
for field_name, field_value in body.model_dump(exclude_none=True).items():
|
||||
if hasattr(project, field_name):
|
||||
setattr(project, field_name, field_value)
|
||||
|
||||
orm.commit()
|
||||
|
||||
return StatusResponse(
|
||||
success=True,
|
||||
message="Deployment configuration updated successfully",
|
||||
)
|
||||
|
||||
|
||||
class InitiateBuildView(BaseDeploymentView):
|
||||
async def __call__(
|
||||
self,
|
||||
project_id: str,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> DeploymentStatusResponse:
|
||||
"""
|
||||
Build image only without deploying.
|
||||
|
||||
This endpoint builds the Docker image and pushes it to the registry
|
||||
but does not create any Kubernetes deployment resources.
|
||||
"""
|
||||
project: HostingProjectModel = await self.get_hosting_project(orm, project_id)
|
||||
|
||||
# Queue the build job for background processing
|
||||
job_id = queue_task(
|
||||
TaskType.BUILD,
|
||||
config=project.deployment_config,
|
||||
project_id=project.id,
|
||||
)
|
||||
|
||||
return DeploymentStatusResponse(
|
||||
success=True,
|
||||
message="Image build queued successfully",
|
||||
job_id=job_id,
|
||||
)
|
||||
|
||||
|
||||
class InitiateDeploymentView(BaseDeploymentView):
|
||||
async def __call__(
|
||||
self,
|
||||
project_id: str,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> DeploymentStatusResponse:
|
||||
"""
|
||||
Initiate a deployment for a project.
|
||||
|
||||
Takes config from the `HostingProjectModel` and queues a deployment job.
|
||||
"""
|
||||
project: HostingProjectModel = await self.get_hosting_project(orm, project_id)
|
||||
|
||||
job_id = queue_task(
|
||||
TaskType.SERVE,
|
||||
config=project.deployment_config,
|
||||
project_id=project.id,
|
||||
)
|
||||
|
||||
return DeploymentStatusResponse(
|
||||
success=True,
|
||||
message="Deployment initiated successfully",
|
||||
job_id=job_id,
|
||||
)
|
||||
|
||||
|
||||
class InitiateRunView(BaseDeploymentView):
|
||||
async def __call__(
|
||||
self,
|
||||
project_id: str,
|
||||
body: RunJobRequest,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> DeploymentStatusResponse:
|
||||
"""
|
||||
Build image and run as a one-time job with input data.
|
||||
|
||||
This endpoint builds the image (if needed) and then runs it as a
|
||||
Kubernetes Job that executes once with the provided input data
|
||||
and returns the result.
|
||||
"""
|
||||
project: HostingProjectModel = await self.get_hosting_project(orm, project_id)
|
||||
|
||||
# Queue the job run for background processing
|
||||
job_id = queue_task(
|
||||
TaskType.RUN,
|
||||
config=project.deployment_config,
|
||||
project_id=project.id,
|
||||
inputs=body.inputs,
|
||||
callback_url=body.callback_url,
|
||||
)
|
||||
|
||||
return DeploymentStatusResponse(
|
||||
success=True,
|
||||
job_id=job_id,
|
||||
message="Job execution queued successfully",
|
||||
)
|
||||
|
||||
|
||||
class DeploymentStatusView(BaseDeploymentView):
|
||||
async def __call__(
|
||||
self,
|
||||
project_id: str,
|
||||
job_id: str,
|
||||
start_date: datetime | None = None,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> DeploymentEventResponse:
|
||||
"""
|
||||
Get a list of events from a specific deployment job.
|
||||
|
||||
If `start_date` is provided, only events after that date will be returned.
|
||||
This is useful for polling new events since the last check.
|
||||
If no `start_date` is provided, all events will be returned.
|
||||
"""
|
||||
project: HostingProjectModel = await self.get_hosting_project(orm, project_id)
|
||||
events: list[BaseEvent] = get_task_events(
|
||||
job_id=job_id,
|
||||
start_time=start_date,
|
||||
)
|
||||
|
||||
return DeploymentEventResponse(
|
||||
events=[
|
||||
DeploymentEventSchema(
|
||||
type=event.event_type,
|
||||
status=event.status,
|
||||
message=event.message,
|
||||
timestamp=event.timestamp,
|
||||
)
|
||||
for event in events
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
class DeploymentBuildLogView(BaseDeploymentView):
|
||||
async def __call__(
|
||||
self,
|
||||
project_id: str,
|
||||
job_id: str,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> StreamingResponse:
|
||||
"""
|
||||
Stream build logs from the builder pod for a specific deployment job.
|
||||
|
||||
Args:
|
||||
project_id: The project ID
|
||||
job_id: The deployment job ID
|
||||
orm: Database session
|
||||
|
||||
Returns:
|
||||
StreamingResponse with plain text logs
|
||||
"""
|
||||
project: HostingProjectModel = await self.get_hosting_project(orm, project_id)
|
||||
|
||||
# Use job_id to find the builder pod (builder pods are now named with job_id)
|
||||
if not (pod := Image.get_builder_pod(project.namespace, job_id)):
|
||||
raise HTTPException(status_code=404, detail=f"Builder pod not found for job {job_id}")
|
||||
|
||||
# TODO this is not flushing mid-stream for some reason.
|
||||
return StreamingResponse(
|
||||
pod.stream_logs(project.namespace),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||
"Pragma": "no-cache",
|
||||
"Expires": "0",
|
||||
"Connection": "keep-alive",
|
||||
# "X-Accel-Buffering": "no",
|
||||
# "X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class DeploymentHistoryView(BaseDeploymentView):
|
||||
async def __call__(
|
||||
self,
|
||||
project_id: str,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> DeploymentHistoryResponse:
|
||||
"""
|
||||
Get a list of deployments and their last status event for a specific project.
|
||||
"""
|
||||
project: HostingProjectModel = await self.get_hosting_project(orm, project_id)
|
||||
|
||||
jobs = []
|
||||
for job in get_tasks(project.namespace, project.id):
|
||||
status_event: BaseEvent = get_task_status(job["job_id"])
|
||||
|
||||
try:
|
||||
status = status_event.status.value
|
||||
message = status_event.message
|
||||
except (IndexError, AttributeError):
|
||||
status = "unknown"
|
||||
message = ""
|
||||
|
||||
jobs.append(
|
||||
DeploymentJobSchema(
|
||||
id=job["job_id"],
|
||||
queued_at=job["queued_at"],
|
||||
status=status,
|
||||
message=message,
|
||||
)
|
||||
)
|
||||
|
||||
return DeploymentHistoryResponse(jobs=jobs)
|
||||
|
||||
|
||||
class ListUserDeploymentsView(BaseDeploymentView):
|
||||
async def __call__(
|
||||
self,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> list[HostingProjectResponse]:
|
||||
"""
|
||||
Get all projects for the current user that have a deployment (HostingProjectModel).
|
||||
Returns combined data from both ProjectModel and HostingProjectModel.
|
||||
"""
|
||||
user_id = self.request.state.session.user_id
|
||||
|
||||
# Get all projects the user has access to
|
||||
projects = ProjectModel.get_all_for_user(orm, user_id)
|
||||
project_ids = [p.id for p in projects]
|
||||
|
||||
if not project_ids:
|
||||
return []
|
||||
|
||||
# Query HostingProjectModel for all records with a matching project id
|
||||
hosting_projects = (
|
||||
orm.query(HostingProjectModel)
|
||||
.filter(HostingProjectModel.id.in_(project_ids))
|
||||
.options(joinedload(HostingProjectModel.project).joinedload(ProjectModel.org))
|
||||
.all()
|
||||
)
|
||||
|
||||
# Create a mapping of project_id to hosting_project for easy lookup
|
||||
hosting_project_map = {hp.id: hp for hp in hosting_projects}
|
||||
|
||||
# Combine data from both models
|
||||
combined_projects = []
|
||||
for project in projects:
|
||||
if project.id in hosting_project_map:
|
||||
hosting_project = hosting_project_map[project.id]
|
||||
|
||||
# Create combined response
|
||||
combined_project = HostingProjectResponse(
|
||||
# Project fields
|
||||
id=project.id,
|
||||
name=project.name,
|
||||
api_key=project.api_key,
|
||||
org_id=project.org_id,
|
||||
environment=project.environment,
|
||||
org=project.org,
|
||||
trace_count=0, # TODO: Add actual trace count if needed
|
||||
# Hosting project fields
|
||||
git_url=hosting_project.git_url,
|
||||
git_branch=hosting_project.git_branch,
|
||||
entrypoint=hosting_project.entrypoint,
|
||||
watch_path=hosting_project.watch_path,
|
||||
user_callback_url=hosting_project.user_callback_url,
|
||||
github_oath_access_token=hosting_project.github_oath_access_token,
|
||||
)
|
||||
|
||||
combined_projects.append(combined_project)
|
||||
|
||||
return combined_projects
|
||||
|
||||
|
||||
class DeleteDeploymentView(BaseDeploymentView):
|
||||
async def __call__(
|
||||
self,
|
||||
project_id: str,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> StatusResponse:
|
||||
"""
|
||||
Delete a deployment for a project.
|
||||
|
||||
This will remove the HostingProjectModel record and clean up any associated resources.
|
||||
"""
|
||||
project: HostingProjectModel = await self.get_hosting_project(orm, project_id)
|
||||
|
||||
# Delete all Kubernetes resources associated with the deployment
|
||||
# This includes deployments, services, ingress, and secrets
|
||||
deployment_name = project_id # Use project_id as deployment name
|
||||
namespace = project.namespace
|
||||
|
||||
try:
|
||||
success = delete_deployment_resources(
|
||||
namespace=namespace, deployment_name=deployment_name, deployment_id=project_id
|
||||
)
|
||||
|
||||
if not success:
|
||||
logger.warning(f"Some Kubernetes resources failed to delete for project {project_id}")
|
||||
# Continue with database deletion even if k8s cleanup had issues
|
||||
except Exception as e:
|
||||
logger.error(f"Error during Kubernetes cleanup for project {project_id}: {e}")
|
||||
# Continue with database deletion even if k8s cleanup failed
|
||||
|
||||
# Delete the HostingProjectModel record
|
||||
orm.delete(project)
|
||||
orm.commit()
|
||||
|
||||
return StatusResponse(
|
||||
success=True,
|
||||
message="Deployment deleted successfully",
|
||||
)
|
||||
@@ -0,0 +1,127 @@
|
||||
import requests
|
||||
from fastapi import Depends, HTTPException
|
||||
from agentops.common.orm import get_orm_session, Session
|
||||
from ...opsboard.models import ProjectModel
|
||||
from ...opsboard.schemas import StatusResponse
|
||||
from ..models import HostingProjectModel
|
||||
from agentops.common.route_config import BaseView
|
||||
from agentops.common.environment import GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET
|
||||
|
||||
|
||||
class GithubOAuthCallbackView(BaseView):
|
||||
"""
|
||||
Exchange GitHub OAuth code for access token and store it in the deploy.projects table.
|
||||
"""
|
||||
|
||||
async def __call__(
|
||||
self,
|
||||
project_id: str,
|
||||
code: str,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> StatusResponse:
|
||||
project = ProjectModel.get_by_id(orm, project_id)
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
if not GITHUB_CLIENT_ID or not GITHUB_CLIENT_SECRET:
|
||||
raise HTTPException(status_code=500, detail="GitHub OAuth not configured in the API")
|
||||
|
||||
# Exchange code for access token
|
||||
token_url = "https://github.com/login/oauth/access_token"
|
||||
headers = {"Accept": "application/json"}
|
||||
data = {
|
||||
"client_id": GITHUB_CLIENT_ID,
|
||||
"client_secret": GITHUB_CLIENT_SECRET,
|
||||
"code": code,
|
||||
}
|
||||
try:
|
||||
resp = requests.post(token_url, headers=headers, data=data)
|
||||
resp.raise_for_status()
|
||||
token_data = resp.json()
|
||||
access_token = token_data.get("access_token")
|
||||
if not access_token:
|
||||
error = token_data.get("error")
|
||||
raise HTTPException(status_code=400, detail="Failed to retrieve access token from GitHub. Error: " + error)
|
||||
|
||||
# Create or update deploy.projects row
|
||||
deploy_project = orm.query(HostingProjectModel).filter_by(id=project.id).first()
|
||||
if not deploy_project:
|
||||
deploy_project = HostingProjectModel(
|
||||
id=project.id,
|
||||
github_oath_access_token=access_token,
|
||||
)
|
||||
orm.add(deploy_project)
|
||||
else:
|
||||
deploy_project.github_oath_access_token = access_token
|
||||
orm.commit()
|
||||
return StatusResponse(message="GitHub access token stored successfully in deploy.projects")
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"GitHub OAuth failed: {str(e)}")
|
||||
|
||||
|
||||
class GithubListReposView(BaseView):
|
||||
"""
|
||||
Use the project's stored GitHub access token to list repos the user has access to.
|
||||
Handles pagination to fetch all repositories.
|
||||
"""
|
||||
|
||||
async def __call__(
|
||||
self,
|
||||
project_id: str,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> list[dict]:
|
||||
project = HostingProjectModel.get_by_id(orm, project_id)
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
if not project.github_oath_access_token:
|
||||
raise HTTPException(status_code=400, detail="No GitHub access token stored for this project")
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {project.github_oath_access_token}",
|
||||
"Accept": "application/vnd.github+json",
|
||||
}
|
||||
|
||||
all_repos = []
|
||||
page = 1
|
||||
per_page = 100 # Maximum allowed by GitHub API
|
||||
|
||||
try:
|
||||
while True:
|
||||
params = {
|
||||
"page": page,
|
||||
"per_page": per_page,
|
||||
"sort": "created", # Sort by creation date
|
||||
"direction": "desc" # Most recent first
|
||||
}
|
||||
|
||||
resp = requests.get("https://api.github.com/user/repos", headers=headers, params=params)
|
||||
resp.raise_for_status()
|
||||
repos = resp.json()
|
||||
|
||||
# If no repos returned, we've reached the end
|
||||
if not repos:
|
||||
break
|
||||
|
||||
# Add repos from this page
|
||||
all_repos.extend([
|
||||
{
|
||||
"id": repo["id"],
|
||||
"name": repo["name"],
|
||||
"full_name": repo["full_name"],
|
||||
"private": repo["private"],
|
||||
"html_url": repo["html_url"],
|
||||
"description": repo.get("description"),
|
||||
}
|
||||
for repo in repos
|
||||
])
|
||||
|
||||
# If we got fewer repos than per_page, we've reached the end
|
||||
if len(repos) < per_page:
|
||||
break
|
||||
|
||||
page += 1
|
||||
|
||||
return all_repos
|
||||
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Failed to fetch repos from GitHub: {str(e)}")
|
||||
@@ -0,0 +1,49 @@
|
||||
## Exporter
|
||||
|
||||
Exporter takes data from the existing schema in SupaBase (postgres) and reformats
|
||||
it into an OTEL format for writing to the ClickHouse backend.
|
||||
|
||||
This service is used both for a one-time migration of all data we have accumulated
|
||||
in postgres, as well as a parallel processor for all data that is still coming into
|
||||
the legacy API endpoint.
|
||||
|
||||
### Legacy API Endpoint
|
||||
|
||||
Data will still be written to the existing server in the existing schema, but at the
|
||||
same time a parallel stream will write otel-formatted data to the ClickHouse backend.
|
||||
|
||||
### One-Time Migration
|
||||
|
||||
A script that can be executed on demand to migrate all data from the existing postgres
|
||||
schema and populate the ClickHouse backend.
|
||||
|
||||
## Next Steps
|
||||
|
||||
- Select a portion of the data from the production database to process.
|
||||
- Spin up dev Supabase postgres instance.
|
||||
- Spin up exporter processing instance.
|
||||
- SELECT ... LIMIT 0, 10000;
|
||||
- Write data into a throwaway ClickHouse instance.
|
||||
- Profit???
|
||||
|
||||
## Noise
|
||||
|
||||
v3 API (v2 in repo)
|
||||
|
||||
/create_session
|
||||
/update_session
|
||||
|
||||
abandon the word session
|
||||
session -> trace
|
||||
|
||||
/create_events
|
||||
/update_events
|
||||
events -> span
|
||||
|
||||
/create_agent
|
||||
agent -> span (that holds other spans)
|
||||
"every event belongs to an agent"
|
||||
|
||||
/sessions/{session_id}/stats # should be superceeded by braelyn API
|
||||
|
||||
92.5 GB of data
|
||||
@@ -0,0 +1,163 @@
|
||||
"""
|
||||
Export data to ClickHouse.
|
||||
|
||||
Takes data from the existing v2.py endpoints and formats it as Spans and Traces.
|
||||
|
||||
Traces and their root spans share the same ID which comes from the Session ID.
|
||||
|
||||
`exporter` is a terrible name, but here we are.
|
||||
"""
|
||||
|
||||
from agentops.api.log_config import logger
|
||||
from agentops.api.db.supabase_client import get_async_supabase
|
||||
from .models import Session, Agent, LLMEvent, ActionEvent, ToolEvent, ErrorEvent
|
||||
from .models import Trace, Span
|
||||
from .processor import (
|
||||
clickhouse_create_trace,
|
||||
clickhouse_create_span,
|
||||
clickhouse_update_span,
|
||||
)
|
||||
|
||||
|
||||
def _filter_for_updated_data(keys: list, data: dict) -> dict:
|
||||
"""Return just the selected fields from the data."""
|
||||
return {k: v for k, v in data.items() if k in keys}
|
||||
|
||||
|
||||
async def _get_project_id(session_id: str) -> str:
|
||||
"""Get the project ID from the session ID."""
|
||||
supabase = await get_async_supabase()
|
||||
session = await supabase.table('sessions').select('project_id').eq('id', session_id).single().execute()
|
||||
return session.data['project_id']
|
||||
|
||||
|
||||
async def create_session(data: dict) -> None:
|
||||
"""Save session data to ClickHouse."""
|
||||
logger.info("Started creating ClickHouse session")
|
||||
session = Session(**data)
|
||||
trace: Trace = await session.to_trace()
|
||||
await clickhouse_create_trace(trace)
|
||||
logger.info(f"Created ClickHouse session as trace {trace}")
|
||||
|
||||
|
||||
async def update_session(data: dict) -> None:
|
||||
"""Update session data for an existing record in ClickHouse."""
|
||||
assert 'id' in data, 'session_id must be provided to update session data.'
|
||||
|
||||
session = Session(**data)
|
||||
trace: Trace = await session.to_trace()
|
||||
span: Span = trace.spans[0]
|
||||
await clickhouse_update_span(span.span_id, span.to_clickhouse_dict())
|
||||
|
||||
|
||||
async def create_agent(data: dict) -> None:
|
||||
"""Save agent data to ClickHouse."""
|
||||
assert 'session_id' in data, 'session_id must be provided to create agent data.'
|
||||
project_id = await _get_project_id(data['session_id'])
|
||||
|
||||
agent = Agent(**data)
|
||||
span = await agent.to_span(
|
||||
trace_id=str(data['session_id']), parent_span_id=str(data['session_id']), project_id=str(project_id)
|
||||
)
|
||||
await clickhouse_create_span(span)
|
||||
logger.info(f"Created ClickHouse agent as span {span}")
|
||||
|
||||
|
||||
async def update_agent(data: dict) -> None:
|
||||
raise NotImplementedError('Pretty sure we never update agent data.')
|
||||
|
||||
|
||||
async def create_llm_event(data: dict) -> None:
|
||||
"""Save LLM event data to ClickHouse."""
|
||||
assert 'session_id' in data, 'session_id must be provided to create LLM event data.'
|
||||
assert 'agent_id' in data, 'agent_id must be provided to create LLM event data.'
|
||||
project_id = await _get_project_id(data['session_id'])
|
||||
|
||||
llm_event = LLMEvent(**data)
|
||||
span: Span = await llm_event.to_span(
|
||||
trace_id=str(data['session_id']), parent_span_id=str(data['agent_id']), project_id=str(project_id)
|
||||
)
|
||||
await clickhouse_create_span(span)
|
||||
logger.info(f"Created ClickHouse LLM event as span {span}")
|
||||
|
||||
|
||||
async def update_llm_event(data: dict) -> None:
|
||||
"""Update LLM event data for an existing record in ClickHouse."""
|
||||
assert 'id' in data, 'id must be provided to update LLM event data.'
|
||||
|
||||
llm_event = LLMEvent(**data)
|
||||
span: Span = await llm_event.to_span()
|
||||
await clickhouse_update_span(span.span_id, span.to_clickhouse_dict())
|
||||
logger.info(f"Updated ClickHouse LLM event as span {span}")
|
||||
|
||||
|
||||
# data['session_id'] = '06246901-8691-4ae3-848e-69aec2d0722b'
|
||||
async def create_action_event(data: dict) -> None:
|
||||
"""Save action event data to ClickHouse."""
|
||||
assert 'session_id' in data, 'session_id must be provided to create action event data.'
|
||||
assert 'agent_id' in data, 'agent_id must be provided to create action event data.'
|
||||
project_id = await _get_project_id(data['session_id'])
|
||||
|
||||
action_event = ActionEvent(**data)
|
||||
span: Span = await action_event.to_span(
|
||||
trace_id=str(data['session_id']), parent_span_id=str(data['agent_id']), project_id=str(project_id)
|
||||
)
|
||||
await clickhouse_create_span(span)
|
||||
logger.info(f"Created ClickHouse action event as span {span}")
|
||||
|
||||
|
||||
async def update_action_event(data: dict) -> None:
|
||||
"""Update action event data for an existing record in ClickHouse."""
|
||||
assert 'id' in data, 'Action Event ID must be provided to update action event data.'
|
||||
|
||||
action_event = ActionEvent(**data)
|
||||
span: Span = await action_event.to_span()
|
||||
await clickhouse_update_span(span.span_id, span.to_clickhouse_dict())
|
||||
logger.info(f"Updated ClickHouse action event as span {span}")
|
||||
|
||||
|
||||
async def create_tool_event(data: dict) -> None:
|
||||
"""Save tool event data to ClickHouse."""
|
||||
assert 'session_id' in data, 'session_id must be provided to create tool event data.'
|
||||
assert 'agent_id' in data, 'agent_id must be provided to create tool event data.'
|
||||
project_id = await _get_project_id(data['session_id'])
|
||||
|
||||
tool_event = ToolEvent(**data)
|
||||
span: Span = await tool_event.to_span(
|
||||
trace_id=str(data['session_id']), parent_span_id=str(data['agent_id']), project_id=str(project_id)
|
||||
)
|
||||
await clickhouse_create_span(span)
|
||||
logger.info(f"Created ClickHouse tool event as span {span}")
|
||||
|
||||
|
||||
async def update_tool_event(data: dict) -> None:
|
||||
"""Update tool event data for an existing record in ClickHouse."""
|
||||
assert 'id' in data, 'id must be provided to update tool event data.'
|
||||
|
||||
tool_event = ToolEvent(**data)
|
||||
span: Span = await tool_event.to_span()
|
||||
await clickhouse_update_span(span.span_id, span.to_clickhouse_dict())
|
||||
logger.info(f"Updated ClickHouse tool event as span {span}")
|
||||
|
||||
|
||||
async def create_error_event(data: dict) -> None:
|
||||
"""Save error event data to ClickHouse."""
|
||||
assert 'session_id' in data, 'session_id must be provided to create error event data.'
|
||||
project_id = await _get_project_id(data['session_id'])
|
||||
|
||||
error_event = ErrorEvent(**data)
|
||||
span: Span = await error_event.to_span(
|
||||
trace_id=str(data['session_id']), parent_span_id=str(data['session_id']), project_id=str(project_id)
|
||||
)
|
||||
await clickhouse_create_span(span)
|
||||
logger.info(f"Created ClickHouse error event as span {span}")
|
||||
|
||||
|
||||
async def update_error_event(data: dict) -> None:
|
||||
"""Update error event data for an existing record in ClickHouse."""
|
||||
assert 'id' in data, 'id must be provided to update error event data.'
|
||||
|
||||
error_event = ErrorEvent(**data)
|
||||
span: Span = await error_event.to_span()
|
||||
await clickhouse_update_span(span.span_id, span.to_clickhouse_dict())
|
||||
logger.info(f"Updated ClickHouse error event as span {span}")
|
||||
@@ -0,0 +1,636 @@
|
||||
from typing import Any
|
||||
import json
|
||||
from uuid import UUID, uuid4
|
||||
from typing import Optional, Union
|
||||
import pydantic
|
||||
from datetime import datetime, timezone
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
|
||||
DEFAULT_SERVICE_NAME = "agentops"
|
||||
DEFAULT_SCOPE_NAME = DEFAULT_SERVICE_NAME
|
||||
DEFAULT_VERSION = "0.3.x"
|
||||
|
||||
|
||||
def datetime_to_ns(dt: Optional[Union[datetime, int, float]]) -> Optional[int]:
|
||||
"""Convert datetime or timestamp to nanoseconds"""
|
||||
if dt is None:
|
||||
return None
|
||||
|
||||
if isinstance(dt, datetime):
|
||||
return int(dt.timestamp() * 1_000_000_000)
|
||||
|
||||
# `int` is probably a millisecond timestamp
|
||||
return int(dt) * 1_000_000
|
||||
|
||||
|
||||
def ns_to_datetime(ns: Optional[int]) -> Optional[datetime]:
|
||||
"""Convert nanoseconds to `datetime`"""
|
||||
if not ns:
|
||||
return None
|
||||
return datetime.fromtimestamp(ns / 1_000_000_000, timezone.utc)
|
||||
|
||||
|
||||
class Trace(pydantic.BaseModel):
|
||||
id: UUID
|
||||
spans: list["Span"] = pydantic.Field(default_factory=list)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Trace(id={self.id})"
|
||||
|
||||
|
||||
class Span(pydantic.BaseModel):
|
||||
"""
|
||||
Span is a representation of a single operation within a trace.
|
||||
It can be a root span or a child span.
|
||||
"""
|
||||
|
||||
name: Optional[str] = None
|
||||
trace_id: Optional[str] = None
|
||||
span_id: str
|
||||
parent_span_id: Optional[str] = None
|
||||
kind: Union[SpanKind, str] = SpanKind.INTERNAL
|
||||
start_time: int = 0
|
||||
end_time: Optional[int] = None
|
||||
project_id: Optional[str] = None
|
||||
service_name: str = DEFAULT_SERVICE_NAME
|
||||
scope_name: str = DEFAULT_SCOPE_NAME
|
||||
scope_version: str = DEFAULT_VERSION
|
||||
resource_attributes: dict[str, str] = pydantic.Field(default_factory=dict)
|
||||
span_attributes: dict[str, str] = pydantic.Field(default_factory=dict)
|
||||
status_code: str = "OK"
|
||||
status_message: str = ""
|
||||
events: list[dict[str, Any]] = pydantic.Field(default_factory=list)
|
||||
links: list[dict[str, Any]] = pydantic.Field(default_factory=list)
|
||||
|
||||
model_config = {
|
||||
'arbitrary_types_allowed': True,
|
||||
}
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Span(span_id={self.span_id}, parent_span_id={self.parent_span_id})"
|
||||
|
||||
def model_post_init(self, __context) -> None:
|
||||
if self.end_time is None:
|
||||
self.end_time = self.start_time
|
||||
|
||||
@property
|
||||
def duration(self) -> int:
|
||||
"""Calculate duration in nanoseconds"""
|
||||
if self.end_time and self.start_time:
|
||||
return self.end_time - self.start_time
|
||||
return 0
|
||||
|
||||
def to_clickhouse_dict(self) -> dict[str, Any]:
|
||||
"""Convert to a dictionary ready for ClickHouse insertion"""
|
||||
|
||||
if self.start_time:
|
||||
timestamp = ns_to_datetime(self.start_time)
|
||||
else:
|
||||
timestamp = datetime.now(timezone.utc)
|
||||
|
||||
# otel_context = SpanContext(
|
||||
# trace_id=trace_id,
|
||||
# span_id=span_id,
|
||||
# is_remote=False,
|
||||
# trace_flags=TraceFlags(0x1), # SAMPLED
|
||||
# trace_state=TraceState()
|
||||
# )
|
||||
|
||||
events_timestamps = []
|
||||
events_names = []
|
||||
events_attributes = []
|
||||
|
||||
for event in self.events:
|
||||
try:
|
||||
event_timestamp = event.get('timestamp', 0)
|
||||
events_timestamps.append(
|
||||
datetime.fromtimestamp(event_timestamp / 1_000_000_000, timezone.utc)
|
||||
)
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
# Fallback if timestamp is invalid
|
||||
events_timestamps.append(timestamp)
|
||||
|
||||
events_names.append(event.get('name', ''))
|
||||
events_attributes.append(event.get('attributes', {}))
|
||||
|
||||
links_trace_ids = []
|
||||
links_span_ids = []
|
||||
links_trace_states = []
|
||||
links_attributes = []
|
||||
|
||||
for link in self.links:
|
||||
links_trace_ids.append(link.get('trace_id', ''))
|
||||
links_span_ids.append(link.get('span_id', ''))
|
||||
links_trace_states.append(link.get('trace_state', ''))
|
||||
links_attributes.append(link.get('attributes', {}))
|
||||
|
||||
if not isinstance(self.resource_attributes, dict):
|
||||
self.resource_attributes = {}
|
||||
self.resource_attributes["agentops.project.id"] = self.project_id
|
||||
|
||||
# Schema from ClickHouse via `DESCRIBE` otel_traces;
|
||||
# Timestamp DateTime64(9)
|
||||
# TraceId String
|
||||
# SpanId String
|
||||
# ParentSpanId String
|
||||
# TraceState String
|
||||
# SpanName LowCardinality(String)
|
||||
# SpanKind LowCardinality(String)
|
||||
# ServiceName LowCardinality(String)
|
||||
# ResourceAttributes Map(LowCardinality(String), String)
|
||||
# ScopeName String
|
||||
# ScopeVersion String
|
||||
# SpanAttributes Map(LowCardinality(String), String)
|
||||
# Duration Int64
|
||||
# StatusCode LowCardinality(String)
|
||||
# StatusMessage String
|
||||
# Events.Timestamp Array(DateTime64(9))
|
||||
# Events.Name Array(LowCardinality(String))
|
||||
# Events.Attributes Array(Map(LowCardinality(String), String))
|
||||
# Links.TraceId Array(String)
|
||||
# Links.SpanId Array(String)
|
||||
# Links.TraceState Array(String)
|
||||
# Links.Attributes Array(Map(LowCardinality(String), String))
|
||||
# ProjectId String
|
||||
return {
|
||||
"Timestamp": timestamp,
|
||||
"TraceId": self.trace_id,
|
||||
"SpanId": self.span_id,
|
||||
"ParentSpanId": self.parent_span_id,
|
||||
"TraceState": "",
|
||||
"SpanName": self.name,
|
||||
"SpanKind": self.kind.name if isinstance(self.kind, SpanKind) else self.kind,
|
||||
"ServiceName": self.service_name,
|
||||
"ResourceAttributes": self.resource_attributes,
|
||||
"ScopeName": self.scope_name,
|
||||
"ScopeVersion": self.scope_version,
|
||||
"SpanAttributes": self.span_attributes,
|
||||
"Duration": self.duration,
|
||||
"StatusCode": self.status_code,
|
||||
"StatusMessage": self.status_message,
|
||||
"Events.Timestamp": events_timestamps,
|
||||
"Events.Name": events_names,
|
||||
"Events.Attributes": events_attributes,
|
||||
"Links.TraceId": links_trace_ids,
|
||||
"Links.SpanId": links_span_ids,
|
||||
"Links.TraceState": links_trace_states,
|
||||
"Links.Attributes": links_attributes,
|
||||
}
|
||||
|
||||
|
||||
class BaseModel(pydantic.BaseModel):
|
||||
model_config = {
|
||||
'arbitrary_types_allowed': True,
|
||||
}
|
||||
|
||||
|
||||
class Session(BaseModel):
|
||||
"""
|
||||
Session renamed to Trace
|
||||
"""
|
||||
|
||||
id: UUID
|
||||
project_id: Optional[UUID] = None
|
||||
init_timestamp: Optional[datetime] = None
|
||||
end_timestamp: Optional[datetime] = None
|
||||
tags: Optional[Union[str, list]] = None
|
||||
end_state: Optional[str] = None
|
||||
end_state_reason: Optional[str] = None
|
||||
video: Optional[str] = None
|
||||
host_env: Optional[dict] = None
|
||||
project_id_secondary: Optional[dict] = None
|
||||
|
||||
async def to_trace(self) -> Trace:
|
||||
"""Convert a Session to a Trace with spans"""
|
||||
span = Span(
|
||||
name="session",
|
||||
trace_id=str(self.id),
|
||||
span_id=str(self.id), # TODO this is the same as trace_id
|
||||
parent_span_id=None, # parent span has no parent
|
||||
kind=SpanKind.SERVER,
|
||||
start_time=datetime_to_ns(self.init_timestamp),
|
||||
end_time=datetime_to_ns(self.end_timestamp),
|
||||
project_id=str(self.project_id),
|
||||
service_name=DEFAULT_SERVICE_NAME,
|
||||
scope_name=f"{DEFAULT_SCOPE_NAME}.session",
|
||||
scope_version=DEFAULT_VERSION,
|
||||
resource_attributes={
|
||||
"host.name": str(self.host_env) if self.host_env else "unknown",
|
||||
"service.name": DEFAULT_SERVICE_NAME,
|
||||
},
|
||||
span_attributes={
|
||||
"session.id": str(self.id),
|
||||
"session.end_state": self.end_state or "",
|
||||
"session.end_state_reason": self.end_state_reason or "",
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
if self.tags:
|
||||
if not isinstance(self.tags, list):
|
||||
self.tags = [self.tags]
|
||||
for i, value in enumerate(self.tags):
|
||||
span.span_attributes[f"session.tag.{i}"] = str(value)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
trace = Trace(id=self.id)
|
||||
trace.spans.append(span)
|
||||
return trace
|
||||
|
||||
|
||||
class Agent(BaseModel):
|
||||
"""
|
||||
Agent becomes a (parent) Span
|
||||
"""
|
||||
|
||||
id: UUID
|
||||
session_id: Optional[UUID] = None
|
||||
name: Optional[str] = None
|
||||
logs: Optional[str] = None
|
||||
|
||||
async def to_span(
|
||||
self,
|
||||
trace_id: Optional[str] = None,
|
||||
parent_span_id: Optional[str] = None,
|
||||
project_id: Optional[str] = None,
|
||||
) -> Span:
|
||||
"""Convert an Agent to a Span"""
|
||||
span_attributes = {
|
||||
"agent.id": str(self.id),
|
||||
"agent.name": self.name or "",
|
||||
"session.id": str(self.session_id),
|
||||
}
|
||||
|
||||
events = []
|
||||
if self.logs:
|
||||
events.append(
|
||||
{
|
||||
"timestamp": 0, # we don't have a timestamp
|
||||
"name": "logs",
|
||||
"attributes": {"log.message": self.logs},
|
||||
}
|
||||
)
|
||||
|
||||
return Span(
|
||||
name=f"agent:{self.name}" if self.name else f"agent:{self.id}",
|
||||
trace_id=trace_id,
|
||||
span_id=str(self.id),
|
||||
parent_span_id=parent_span_id,
|
||||
kind=SpanKind.INTERNAL,
|
||||
project_id=project_id,
|
||||
service_name=DEFAULT_SERVICE_NAME,
|
||||
scope_name=f"{DEFAULT_SCOPE_NAME}.agent",
|
||||
scope_version=DEFAULT_VERSION,
|
||||
resource_attributes={},
|
||||
span_attributes=span_attributes,
|
||||
events=events,
|
||||
)
|
||||
|
||||
|
||||
class ActionEvent(BaseModel):
|
||||
"""
|
||||
Action becomes a (child) Span
|
||||
"""
|
||||
|
||||
id: UUID
|
||||
session_id: Optional[UUID] = None
|
||||
agent_id: Optional[UUID] = None
|
||||
action_type: Optional[str] = None
|
||||
logs: Optional[str] = None
|
||||
screenshot: Optional[str] = None
|
||||
params: Optional[str] = None
|
||||
returns: Optional[str] = None
|
||||
init_timestamp: Optional[datetime] = None
|
||||
end_timestamp: Optional[datetime] = None
|
||||
|
||||
async def to_span(
|
||||
self,
|
||||
trace_id: Optional[str] = None,
|
||||
parent_span_id: Optional[str] = None,
|
||||
project_id: Optional[str] = None,
|
||||
) -> Span:
|
||||
"""Convert an ActionEvent to a Span"""
|
||||
span_attributes = {
|
||||
"action.id": str(self.id),
|
||||
"action.type": self.action_type or "",
|
||||
"session.id": str(self.session_id),
|
||||
"agent.id": str(self.agent_id),
|
||||
}
|
||||
|
||||
if self.params:
|
||||
if isinstance(self.params, dict):
|
||||
span_attributes["action.params"] = json.dumps(self.params)
|
||||
else:
|
||||
span_attributes["action.params"] = str(self.params)
|
||||
|
||||
if self.returns:
|
||||
if isinstance(self.returns, dict):
|
||||
span_attributes["action.returns"] = json.dumps(self.returns)
|
||||
else:
|
||||
span_attributes["action.returns"] = str(self.returns)
|
||||
|
||||
if self.screenshot:
|
||||
span_attributes["action.screenshot"] = self.screenshot
|
||||
|
||||
init_timestamp_ns = datetime_to_ns(self.init_timestamp)
|
||||
events = []
|
||||
if self.logs:
|
||||
events.append(
|
||||
{"timestamp": init_timestamp_ns, "name": "logs", "attributes": {"log.message": self.logs}}
|
||||
)
|
||||
|
||||
return Span(
|
||||
name=f"action:{self.action_type or 'unknown'}",
|
||||
trace_id=trace_id,
|
||||
span_id=str(self.id),
|
||||
parent_span_id=parent_span_id,
|
||||
kind=SpanKind.INTERNAL,
|
||||
start_time=init_timestamp_ns,
|
||||
end_time=datetime_to_ns(self.end_timestamp),
|
||||
project_id=project_id,
|
||||
service_name=DEFAULT_SERVICE_NAME,
|
||||
scope_name=f"{DEFAULT_SCOPE_NAME}.action",
|
||||
scope_version=DEFAULT_VERSION,
|
||||
resource_attributes={},
|
||||
span_attributes=span_attributes,
|
||||
events=events,
|
||||
)
|
||||
|
||||
|
||||
class LLMEvent(BaseModel):
|
||||
"""
|
||||
LLMEvent becomes a (child) Span
|
||||
"""
|
||||
|
||||
id: UUID
|
||||
session_id: Optional[UUID] = None
|
||||
agent_id: Optional[UUID] = None
|
||||
thread_id: Optional[UUID] = None
|
||||
prompt: Optional[dict] = None
|
||||
completion: Optional[dict] = None
|
||||
model: Optional[str] = None
|
||||
prompt_tokens: Optional[int] = None
|
||||
completion_tokens: Optional[int] = None
|
||||
cost: Optional[float] = None
|
||||
promptarmor_flag: Optional[bool] = None
|
||||
params: Optional[Union[str, dict]] = None
|
||||
returns: Optional[Union[str, dict]] = None
|
||||
init_timestamp: Optional[datetime] = None
|
||||
end_timestamp: Optional[datetime] = None
|
||||
|
||||
async def to_span(
|
||||
self,
|
||||
trace_id: Optional[str] = None,
|
||||
parent_span_id: Optional[str] = None,
|
||||
project_id: Optional[str] = None,
|
||||
) -> Span:
|
||||
"""Convert an LLMEvent to a Span with GenAI semantic conventions"""
|
||||
|
||||
# Use GenAI semantic conventions for span attributes
|
||||
# See: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai.md
|
||||
|
||||
# {
|
||||
# "gen_ai.completion.0.content": "Why couldn't the bicycle stand up by itself? It was two tired.",
|
||||
# "gen_ai.completion.0.finish_reason": "stop",
|
||||
# "gen_ai.completion.0.role": "assistant",
|
||||
# "gen_ai.openai.api_base": "https://api.openai.com/v1/",
|
||||
# "gen_ai.prompt.0.content": "Write a one-line joke",
|
||||
# "gen_ai.prompt.0.role": "user",
|
||||
# "gen_ai.request.model": "gpt-3.5-turbo",
|
||||
# "gen_ai.response.id": "chatcmpl-B9ekm6iX1GDInqhtj5XlmIqFHamFf",
|
||||
# "gen_ai.response.model": "gpt-3.5-turbo-0125",
|
||||
# "gen_ai.system": "OpenAI",
|
||||
# "gen_ai.usage.completion_tokens": "16",
|
||||
# "gen_ai.usage.prompt_tokens": "12",
|
||||
# "llm.headers": "None",
|
||||
# "llm.is_streaming": "false",
|
||||
# "llm.request.type": "chat",
|
||||
# "llm.usage.total_tokens": "28"
|
||||
# }
|
||||
|
||||
span_attributes = {
|
||||
"llm.id": str(self.id),
|
||||
"llm.model": self.model if self.model else "",
|
||||
"llm.prompt_tokens": str(self.prompt_tokens),
|
||||
"llm.completion_tokens": str(self.completion_tokens),
|
||||
"llm.total_tokens": str(self.prompt_tokens + self.completion_tokens),
|
||||
"llm.cost": str(self.cost) if self.cost is not None else "0.0",
|
||||
"session.id": str(self.session_id),
|
||||
"agent.id": str(self.agent_id),
|
||||
"thread.id": str(self.thread_id) if self.thread_id else "",
|
||||
"llm.is_streaming": "false",
|
||||
"llm.request.type": "chat",
|
||||
"gen_ai.openai.api_base": "https://api.openai.com/v1/",
|
||||
"gen_ai.usage.prompt_tokens": str(self.prompt_tokens),
|
||||
"gen_ai.usage.completion_tokens": str(self.completion_tokens),
|
||||
}
|
||||
|
||||
try:
|
||||
prompts = self.prompt.get('messages', self.prompt)
|
||||
if not isinstance(prompts, list):
|
||||
prompts = [prompts]
|
||||
for i, prompt in enumerate(prompts):
|
||||
if not isinstance(prompt, dict):
|
||||
continue
|
||||
if 'content' in prompt:
|
||||
content = prompt['content']
|
||||
elif 'string' in prompt:
|
||||
content = prompt['string']
|
||||
elif 'message' in prompt:
|
||||
content = prompt['message']
|
||||
else:
|
||||
content = prompt
|
||||
span_attributes[f"gen_ai.prompt.{i}.content"] = str(content)
|
||||
span_attributes[f"gen_ai.prompt.{i}.role"] = str(prompt.get('role', ""))
|
||||
except (KeyError, TypeError):
|
||||
span_attributes["gen_ai.prompt"] = self.prompt
|
||||
|
||||
try:
|
||||
completions = self.completion.get('messages', self.completion)
|
||||
if not isinstance(completions, list):
|
||||
completions = [completions]
|
||||
for i, completion in enumerate(completions):
|
||||
if not isinstance(completion, dict):
|
||||
continue
|
||||
span_attributes[f"gen_ai.completion.{i}.content"] = str(completion.get('content', ""))
|
||||
span_attributes[f"gen_ai.completion.{i}.finish_reason"] = "stop"
|
||||
span_attributes[f"gen_ai.completion.{i}.role"] = str(completion.get('role', ""))
|
||||
# span_attributes[f"gen_ai.completion.{i}.tool_calls"] = json.dumps(completion.get('role', []))
|
||||
except (KeyError, TypeError):
|
||||
span_attributes["gen_ai.completion"] = self.completion
|
||||
|
||||
if self.promptarmor_flag is not None:
|
||||
span_attributes["llm.promptarmor_flag"] = str(self.promptarmor_flag).lower()
|
||||
|
||||
span_attributes["gen_ai.system"] = "llm"
|
||||
span_attributes["gen_ai.operation.name"] = "chat"
|
||||
span_attributes["gen_ai.request.model"] = self.model if self.model else ""
|
||||
span_attributes["gen_ai.response.model"] = self.model if self.model else ""
|
||||
|
||||
if self.params:
|
||||
if isinstance(self.params, dict):
|
||||
span_attributes["gen_ai.request.parameters"] = json.dumps(self.params)
|
||||
else:
|
||||
span_attributes["gen_ai.request.parameters"] = str(self.params)
|
||||
|
||||
if self.returns:
|
||||
if isinstance(self.returns, dict):
|
||||
span_attributes["gen_ai.response.metadata"] = json.dumps(self.returns)
|
||||
else:
|
||||
span_attributes["gen_ai.response.metadata"] = str(self.returns)
|
||||
|
||||
init_timestamp_ns = datetime_to_ns(self.init_timestamp)
|
||||
end_timestamp_ns = datetime_to_ns(self.end_timestamp) or init_timestamp_ns
|
||||
|
||||
return Span(
|
||||
name=f"llm:{self.model}",
|
||||
trace_id=trace_id,
|
||||
span_id=str(self.id),
|
||||
parent_span_id=parent_span_id,
|
||||
kind=SpanKind.CLIENT,
|
||||
start_time=init_timestamp_ns,
|
||||
end_time=end_timestamp_ns,
|
||||
project_id=project_id,
|
||||
service_name=DEFAULT_SERVICE_NAME,
|
||||
scope_name=f"{DEFAULT_SCOPE_NAME}.llm",
|
||||
scope_version=DEFAULT_VERSION,
|
||||
resource_attributes={},
|
||||
span_attributes=span_attributes,
|
||||
events=[],
|
||||
)
|
||||
|
||||
|
||||
class ToolEvent(BaseModel):
|
||||
"""
|
||||
ToolEvent becomes a (child) Span
|
||||
"""
|
||||
|
||||
id: UUID
|
||||
session_id: Optional[UUID] = None
|
||||
agent_id: Optional[UUID] = None
|
||||
name: Optional[str] = None
|
||||
logs: Optional[str] = None
|
||||
params: Optional[Union[str, dict]] = None
|
||||
returns: Optional[Union[dict, str]] = None
|
||||
init_timestamp: Optional[datetime] = None
|
||||
end_timestamp: Optional[datetime] = None
|
||||
|
||||
async def to_span(
|
||||
self,
|
||||
trace_id: Optional[str] = None,
|
||||
parent_span_id: Optional[str] = None,
|
||||
project_id: Optional[str] = None,
|
||||
) -> Span:
|
||||
"""Convert a ToolEvent to a Span"""
|
||||
span_attributes = {
|
||||
"tool.id": str(self.id),
|
||||
"tool.name": self.name,
|
||||
"session.id": str(self.session_id),
|
||||
"agent.id": str(self.agent_id),
|
||||
"gen_ai.tool.name": self.name,
|
||||
}
|
||||
|
||||
if self.params:
|
||||
if isinstance(self.params, dict):
|
||||
span_attributes["tool.params"] = json.dumps(self.params)
|
||||
else:
|
||||
span_attributes["tool.params"] = str(self.params)
|
||||
|
||||
if self.returns:
|
||||
if isinstance(self.returns, dict):
|
||||
span_attributes["tool.returns"] = json.dumps(self.returns)
|
||||
else:
|
||||
span_attributes["tool.returns"] = str(self.returns)
|
||||
|
||||
init_timestamp_ns = datetime_to_ns(self.init_timestamp)
|
||||
events = []
|
||||
if self.logs:
|
||||
events.append(
|
||||
{"timestamp": init_timestamp_ns, "name": "logs", "attributes": {"log.message": self.logs}}
|
||||
)
|
||||
|
||||
return Span(
|
||||
name=f"tool:{self.name}",
|
||||
trace_id=trace_id,
|
||||
span_id=str(self.id),
|
||||
parent_span_id=parent_span_id,
|
||||
kind=SpanKind.INTERNAL,
|
||||
start_time=init_timestamp_ns,
|
||||
end_time=datetime_to_ns(self.end_timestamp),
|
||||
project_id=project_id,
|
||||
service_name=DEFAULT_SERVICE_NAME,
|
||||
scope_name=f"{DEFAULT_SCOPE_NAME}.tool",
|
||||
scope_version=DEFAULT_VERSION,
|
||||
resource_attributes={},
|
||||
span_attributes=span_attributes,
|
||||
events=events,
|
||||
)
|
||||
|
||||
|
||||
class ErrorEvent(BaseModel):
|
||||
"""
|
||||
ErrorEvent becomes a (child) Span
|
||||
"""
|
||||
|
||||
id: Optional[int] = pydantic.Field(default=uuid4())
|
||||
session_id: Optional[UUID] = None
|
||||
trigger_event_id: Optional[UUID] = None
|
||||
trigger_event_type: Optional[str] = None
|
||||
error_type: Optional[str] = None
|
||||
code: Optional[str] = None
|
||||
details: Optional[str] = None
|
||||
logs: Optional[str] = None
|
||||
timestamp: Optional[datetime] = None
|
||||
|
||||
async def to_span(
|
||||
self,
|
||||
trace_id: Optional[str] = None,
|
||||
parent_span_id: Optional[str] = None,
|
||||
project_id: Optional[str] = None,
|
||||
) -> Span:
|
||||
"""Convert an ErrorEvent to a Span"""
|
||||
span_attributes = {
|
||||
"error.type": self.error_type or "unknown_error",
|
||||
"error.code": self.code if self.code else "",
|
||||
"session.id": str(self.session_id),
|
||||
"trigger_event.id": str(self.trigger_event_id) if self.trigger_event_id else "",
|
||||
"trigger_event.type": str(self.trigger_event_type) if self.trigger_event_type else "",
|
||||
}
|
||||
|
||||
timestamp_ns = datetime_to_ns(self.timestamp)
|
||||
events = []
|
||||
if self.details:
|
||||
events.append(
|
||||
{
|
||||
"timestamp": timestamp_ns,
|
||||
"name": "error.details",
|
||||
"attributes": {"error.details": self.details},
|
||||
}
|
||||
)
|
||||
if self.logs:
|
||||
events.append(
|
||||
{"timestamp": timestamp_ns, "name": "logs", "attributes": {"log.message": self.logs}}
|
||||
)
|
||||
|
||||
return Span(
|
||||
name=f"error:{self.error_type or 'unknown'}",
|
||||
trace_id=trace_id,
|
||||
span_id=str(self.id),
|
||||
parent_span_id=parent_span_id,
|
||||
kind=SpanKind.INTERNAL,
|
||||
start_time=timestamp_ns,
|
||||
end_time=timestamp_ns, # same as start for point-in-time event
|
||||
project_id=project_id,
|
||||
service_name=DEFAULT_SERVICE_NAME,
|
||||
scope_name=f"{DEFAULT_SCOPE_NAME}.error",
|
||||
scope_version=DEFAULT_VERSION,
|
||||
resource_attributes={},
|
||||
span_attributes=span_attributes,
|
||||
status_code="ERROR",
|
||||
status_message=self.details
|
||||
if self.details and len(self.details) < 100
|
||||
else (self.error_type or "unknown_error"),
|
||||
events=events,
|
||||
)
|
||||
@@ -0,0 +1,577 @@
|
||||
"""
|
||||
Processor
|
||||
---------
|
||||
The processor handles acquiring a connection to each endpoint and marshalling the data
|
||||
between each.
|
||||
|
||||
This module serves as both an internal API for working with the interchange of data between
|
||||
the Supabase and ClickHouse databases, as well as a CLI tool for exporting data from Supabase
|
||||
to ClickHouse as a batch operation.
|
||||
"""
|
||||
|
||||
from typing import Any, Optional, AsyncGenerator
|
||||
import warnings
|
||||
import asyncio
|
||||
import os
|
||||
import psycopg
|
||||
import psycopg_pool
|
||||
from clickhouse_driver.util.escape import escape_param as _clickhouse_escape_param
|
||||
|
||||
from agentops.api.db.clickhouse_client import get_async_clickhouse
|
||||
from .models import BaseModel, Session, Agent, ActionEvent, LLMEvent, ToolEvent, ErrorEvent
|
||||
from .models import Trace, Span
|
||||
|
||||
|
||||
EXPORT_TABLES_MODELS: dict[str, BaseModel] = {
|
||||
'sessions': Session,
|
||||
'agents': Agent,
|
||||
'actions': ActionEvent,
|
||||
'llms': LLMEvent,
|
||||
'tools': ToolEvent,
|
||||
'errors': ErrorEvent,
|
||||
}
|
||||
EXPORT_AS_SPANS = (
|
||||
'agents',
|
||||
'actions',
|
||||
'llms',
|
||||
'tools',
|
||||
'errors',
|
||||
)
|
||||
IMPORT_TABLE_NAME = 'otel_traces'
|
||||
|
||||
# Supabase connection pooling for export
|
||||
SUPABASE_MIN_POOL_SIZE = 12
|
||||
SUPABASE_MAX_POOL_SIZE = 24
|
||||
|
||||
# DRY_RUN does not write data to ClickHouse
|
||||
DRY_RUN = False
|
||||
|
||||
# Pagination for exporting data from Supabase
|
||||
PAGE_NUMBER = 0
|
||||
# Cutoff after a certain number of pages
|
||||
MAX_PAGES = None
|
||||
|
||||
# Timeout for writing a trace to ClickHouse
|
||||
TIMEOUT = 240
|
||||
# Number of rows to fetch from Supabase per page for export
|
||||
BATCH_ROW_COUNT = 1000
|
||||
|
||||
# Maximum number of concurrent workers
|
||||
MAX_CONCURRENT = 42
|
||||
PARALLEL_READS = 21
|
||||
|
||||
# Filenames for persistent state
|
||||
DROPPED_RECORDS_FILENAME = 'dropped_records.csv'
|
||||
LAST_SESSION_ID_FILENAME = 'last_session_id.txt'
|
||||
|
||||
# Global variables that will be initialized in main() or init functions
|
||||
_last_session_file = None
|
||||
LAST_SESSION_ID = None
|
||||
|
||||
|
||||
def write_dropped_record(table: str, id: Any, exception: Exception) -> None:
|
||||
"""Make a note of a record that was dropped during processing."""
|
||||
with open(DROPPED_RECORDS_FILENAME, 'a') as f:
|
||||
msg = str(exception).replace('"', "'").replace("\n", " ~ ")
|
||||
f.write(f"{table},{str(id)},\"{msg}\"\n")
|
||||
|
||||
|
||||
def write_last_session_id(session_id: Any) -> None:
|
||||
"""Write the last session_id by truncating and writing to the already open file."""
|
||||
print(session_id)
|
||||
if _last_session_file:
|
||||
_last_session_file.seek(0)
|
||||
_last_session_file.truncate()
|
||||
_last_session_file.write(str(session_id))
|
||||
_last_session_file.flush()
|
||||
|
||||
|
||||
# Supabase connection pool instance
|
||||
_supabase_pool: Optional[Any] = None
|
||||
|
||||
|
||||
def get_supabase_pool() -> Any:
|
||||
"""Get a read-only connection pool to Supabase."""
|
||||
global _supabase_pool
|
||||
|
||||
host = os.getenv('SUPABASE_HOST')
|
||||
port = os.getenv('SUPABASE_PORT')
|
||||
database = os.getenv('SUPABASE_DATABASE')
|
||||
user = os.getenv('SUPABASE_USER')
|
||||
password = os.getenv('SUPABASE_PASSWORD')
|
||||
|
||||
if _supabase_pool is None:
|
||||
_supabase_pool = psycopg_pool.AsyncConnectionPool(
|
||||
f"postgresql://{user}:{password}@{host}:{port}/{database}",
|
||||
min_size=SUPABASE_MIN_POOL_SIZE,
|
||||
max_size=SUPABASE_MAX_POOL_SIZE,
|
||||
# configure=lambda c: c.execute("SET default_transaction_read_only = on")
|
||||
)
|
||||
return _supabase_pool
|
||||
|
||||
|
||||
async def close_supabase_pool() -> None:
|
||||
"""Close the connection pool to Supabase."""
|
||||
global _supabase_pool
|
||||
if _supabase_pool is not None:
|
||||
await _supabase_pool.close()
|
||||
_supabase_pool = None
|
||||
|
||||
|
||||
class SupabaseExporterMeta(type):
|
||||
def __class_getitem__(cls, model_class: BaseModel) -> 'SupabaseExporter':
|
||||
if model_class not in EXPORT_TABLES_MODELS.values():
|
||||
raise ValueError(model_class.__name__)
|
||||
|
||||
table_name = [k for k, v in EXPORT_TABLES_MODELS.items() if v == model_class][0]
|
||||
return SupabaseExporter(table_name, model_class)
|
||||
|
||||
|
||||
class SupabaseExporter(metaclass=SupabaseExporterMeta):
|
||||
"""
|
||||
Exporter that connects to a Supabase table and fetches records as model instances.
|
||||
|
||||
Usage:
|
||||
```
|
||||
sessions = SupabaseExporter['sessions']
|
||||
async for session in sessions.fetchall("SELECT * FROM {table_name}"):
|
||||
print(session)
|
||||
```
|
||||
`table_name` is always populated with the table name of the model class.
|
||||
|
||||
Extra parameters can be passed to the fetchall method as keyword arguments.
|
||||
```
|
||||
async for session in sessions.fetchall("SELECT * FROM {table_name} WHERE id = '{id}'", id='123'):
|
||||
print(session)
|
||||
```
|
||||
"""
|
||||
|
||||
table_name: str
|
||||
model_class: BaseModel
|
||||
|
||||
def __init__(self, table_name: str, model_class: BaseModel) -> None:
|
||||
self.table_name = table_name
|
||||
self.model_class = model_class
|
||||
|
||||
def get_model_instance(self, **kwargs) -> BaseModel:
|
||||
try:
|
||||
return self.model_class(**kwargs)
|
||||
except Exception as e:
|
||||
write_dropped_record(self.table_name, kwargs.get('id', 'unknown'), e)
|
||||
|
||||
async def fetchall(self, query: str, **kwargs) -> AsyncGenerator[BaseModel, None]:
|
||||
query = query.format(table_name=self.table_name, **kwargs)
|
||||
async with get_supabase_pool().connection() as conn:
|
||||
# Use a dictionary row factory to get rows as dictionaries
|
||||
async with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
|
||||
await cur.execute(query)
|
||||
for row in await cur.fetchall():
|
||||
yield self.get_model_instance(**row)
|
||||
|
||||
async def fetchone(self, query: str, **kwargs) -> BaseModel:
|
||||
query = query.format(table_name=self.table_name, **kwargs)
|
||||
async with get_supabase_pool().connection() as conn:
|
||||
async with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
|
||||
await cur.execute(query)
|
||||
return self.get_model_instance(**await cur.fetchone())
|
||||
|
||||
|
||||
supabase = SupabaseExporter
|
||||
|
||||
|
||||
async def fetch_all_for_session(model_class: BaseModel, session_id) -> AsyncGenerator[BaseModel, None]:
|
||||
"""Fetch all records for a session from a given table"""
|
||||
query = """
|
||||
SELECT * FROM {table_name}
|
||||
WHERE session_id = '{session_id}'
|
||||
"""
|
||||
exporter = supabase[model_class]
|
||||
async for result in exporter.fetchall(query, session_id=session_id):
|
||||
yield result
|
||||
|
||||
|
||||
async def get_session_as_trace(session: Session) -> Trace:
|
||||
"""Convert a session to a trace with all related spans"""
|
||||
write_last_session_id(session.id)
|
||||
try:
|
||||
trace: Trace = await session.to_trace()
|
||||
parent_span_id = trace.spans[0].span_id
|
||||
except Exception as e:
|
||||
if not session:
|
||||
write_dropped_record('session', 'unknown', e)
|
||||
return
|
||||
write_dropped_record('session', session.id, e)
|
||||
return
|
||||
|
||||
for table_name in EXPORT_AS_SPANS:
|
||||
model_class = EXPORT_TABLES_MODELS[table_name]
|
||||
async for record in fetch_all_for_session(model_class, session.id):
|
||||
try:
|
||||
if isinstance(record, (Agent, ErrorEvent)):
|
||||
# agent and error belong to parent span
|
||||
span = await record.to_span(
|
||||
trace_id=trace.id, parent_span_id=parent_span_id, project_id=str(session.project_id)
|
||||
)
|
||||
elif isinstance(record, (ActionEvent, LLMEvent, ToolEvent)):
|
||||
# actions, llms, and tools belong to an agent
|
||||
span = await record.to_span(
|
||||
trace_id=trace.id,
|
||||
parent_span_id=str(record.agent_id),
|
||||
project_id=str(session.project_id),
|
||||
)
|
||||
else:
|
||||
warnings.warn(f"Unknown record type: {type(record)}")
|
||||
continue
|
||||
except Exception as e:
|
||||
table_name = [k for k, v in EXPORT_TABLES_MODELS.items() if v == model_class][0]
|
||||
write_dropped_record(table_name, record.id, e)
|
||||
continue
|
||||
trace.spans.append(span)
|
||||
return trace
|
||||
|
||||
|
||||
async def get_sessions(offset: int, limit: int) -> list[Session]:
|
||||
"""Get raw session records without processing them as traces yet"""
|
||||
query = """
|
||||
SELECT * FROM {table_name}
|
||||
WHERE id > '{last_session_id}'
|
||||
ORDER BY id ASC
|
||||
LIMIT {limit}
|
||||
OFFSET {offset}
|
||||
"""
|
||||
sessions = []
|
||||
lsid = LAST_SESSION_ID if LAST_SESSION_ID else '00000000-0000-0000-0000-000000000000'
|
||||
async for session in supabase[Session].fetchall(query, offset=offset, limit=limit, last_session_id=lsid):
|
||||
sessions.append(session)
|
||||
return sessions
|
||||
|
||||
|
||||
async def get_sessions_as_traces(offset: int, limit: int) -> AsyncGenerator[Trace, None]:
|
||||
"""Get sessions and convert them to traces with parallel processing"""
|
||||
sessions = await get_sessions(offset, limit)
|
||||
for i in range(0, len(sessions), PARALLEL_READS):
|
||||
batch = sessions[i : i + PARALLEL_READS]
|
||||
tasks = [asyncio.create_task(get_session_as_trace(session)) for session in batch]
|
||||
for task in asyncio.as_completed(tasks):
|
||||
trace = await task
|
||||
print(trace.id)
|
||||
yield trace
|
||||
|
||||
|
||||
# Cache for session_id to project_id mapping
|
||||
_SESSION_PROJECT_CACHE = {}
|
||||
_SESSION_PROJECT_CACHE_ORDER = []
|
||||
_SESSION_PROJECT_CACHE_MAX_SIZE = 10000
|
||||
|
||||
|
||||
async def get_project_id_for_session_id(session_id: str) -> str:
|
||||
"""
|
||||
Get the project id for a given session id
|
||||
Caches the result for 10,000 sessions
|
||||
"""
|
||||
if not session_id:
|
||||
print("Warning: Received empty session_id")
|
||||
return None
|
||||
|
||||
# Check cache first
|
||||
if session_id in _SESSION_PROJECT_CACHE:
|
||||
# Move to the end of the order list to mark as recently used
|
||||
# Only try to remove if the session_id is actually in the order list
|
||||
if session_id in _SESSION_PROJECT_CACHE_ORDER:
|
||||
_SESSION_PROJECT_CACHE_ORDER.remove(session_id)
|
||||
_SESSION_PROJECT_CACHE_ORDER.append(session_id)
|
||||
else:
|
||||
# Fix inconsistency by adding to order list if missing
|
||||
_SESSION_PROJECT_CACHE_ORDER.append(session_id)
|
||||
return _SESSION_PROJECT_CACHE[session_id]
|
||||
|
||||
query = """
|
||||
SELECT * FROM sessions
|
||||
WHERE id = '{session_id}'
|
||||
LIMIT 1
|
||||
"""
|
||||
result = await supabase[Session].fetchone(query, session_id=session_id)
|
||||
if result:
|
||||
project_id = result.project_id
|
||||
# Add to cache
|
||||
if len(_SESSION_PROJECT_CACHE_ORDER) >= _SESSION_PROJECT_CACHE_MAX_SIZE:
|
||||
# Remove oldest entry
|
||||
oldest_session_id = _SESSION_PROJECT_CACHE_ORDER.pop(0)
|
||||
del _SESSION_PROJECT_CACHE[oldest_session_id]
|
||||
_SESSION_PROJECT_CACHE[session_id] = project_id
|
||||
_SESSION_PROJECT_CACHE_ORDER.append(session_id)
|
||||
return project_id
|
||||
raise Exception(f"Warning: No project_id found for session_id: {session_id}")
|
||||
|
||||
|
||||
async def get_v2_sourced_rows(limit: int, offset: int) -> list:
|
||||
"""Get span from ClickHouse that were supplied by v2 exporter"""
|
||||
client = await get_async_clickhouse()
|
||||
query = """
|
||||
SELECT * FROM otel_2.otel_traces
|
||||
WHERE mapContains(SpanAttributes, 'session.id')
|
||||
LIMIT {limit}
|
||||
OFFSET {offset}
|
||||
"""
|
||||
try:
|
||||
query = query.format(table_name=IMPORT_TABLE_NAME, limit=limit, offset=offset)
|
||||
result = await client.query(query)
|
||||
if result and hasattr(result, 'result_rows') and len(result.result_rows) > 0:
|
||||
rows = []
|
||||
for row in result.result_rows:
|
||||
row_dict = dict(zip(result.column_names, row))
|
||||
rows.append(row_dict)
|
||||
return rows
|
||||
return []
|
||||
except Exception as e:
|
||||
print(f"Error fetching rows: {e}")
|
||||
return []
|
||||
|
||||
|
||||
async def assign_correct_project_id(span_id: str, project_id: str) -> bool:
|
||||
"""Assign the correct project id to each row"""
|
||||
clickhouse_client = await get_async_clickhouse()
|
||||
query = """
|
||||
ALTER TABLE otel_2.{table_name}
|
||||
UPDATE ResourceAttributes = mapUpdate(ResourceAttributes, map('agentops.project.id', "{project_id}"))
|
||||
WHERE SpanId = {span_id};
|
||||
"""
|
||||
if project_id is None:
|
||||
raise Exception(f"Project id is None for span_id: {span_id}")
|
||||
|
||||
query = query.format(table_name=IMPORT_TABLE_NAME, project_id=project_id, span_id=span_id)
|
||||
result = await clickhouse_client.query(query)
|
||||
if result.rows_affected > 0:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
async def count_v2_sourced_rows() -> int:
|
||||
"""Count the number of rows in the v2 sourced table"""
|
||||
clickhouse_client = await get_async_clickhouse()
|
||||
query = """
|
||||
SELECT COUNT(1) FROM otel_2.otel_traces
|
||||
WHERE mapContains(SpanAttributes, 'session.id')
|
||||
"""
|
||||
result = await clickhouse_client.query(query)
|
||||
return result.result_rows[0][0]
|
||||
|
||||
|
||||
class _ClickhouseDriverContextShim:
|
||||
# i just need context.server_info.get_timezone()
|
||||
class ServerInfo:
|
||||
def get_timezone(self):
|
||||
return 'UTC' # TODO this is prob not correct
|
||||
|
||||
server_info = ServerInfo()
|
||||
|
||||
|
||||
def clickhouse_escape_param(value: Any) -> str:
|
||||
"""Escape a parameter for use in a ClickHouse query"""
|
||||
# not robust enough to pass a full span for insertion or update :/
|
||||
context = _ClickhouseDriverContextShim()
|
||||
return _clickhouse_escape_param(value, context)
|
||||
|
||||
|
||||
def clickhouse_escape_value(value: str) -> Any:
|
||||
"""Escape a value for use in a ClickHouse query"""
|
||||
# we don't pass the query to the full escape because it seems like `insert`
|
||||
# handles most of it.
|
||||
if value is None:
|
||||
return 'NULL'
|
||||
if isinstance(value, list):
|
||||
return [clickhouse_escape_value(v) for v in value]
|
||||
if isinstance(value, dict):
|
||||
return {k: clickhouse_escape_value(v) for k, v in value.items()}
|
||||
if isinstance(value, int):
|
||||
return str(value)
|
||||
return value
|
||||
|
||||
|
||||
async def clickhouse_create(data: list[dict]) -> None:
|
||||
"""Create a record in ClickHouse"""
|
||||
client = await get_async_clickhouse()
|
||||
|
||||
for i, row in enumerate(data):
|
||||
for key, value in row.items():
|
||||
data[i][key] = clickhouse_escape_value(value)
|
||||
|
||||
if not DRY_RUN:
|
||||
await client.insert(
|
||||
table=IMPORT_TABLE_NAME,
|
||||
data=[list(row.values()) for row in data],
|
||||
column_names=list(data[0].keys()),
|
||||
)
|
||||
else:
|
||||
print(data)
|
||||
|
||||
|
||||
async def clickhouse_create_trace(trace: Trace) -> None:
|
||||
"""Create a trace in ClickHouse"""
|
||||
data = [span.to_clickhouse_dict() for span in trace.spans]
|
||||
await clickhouse_create(data)
|
||||
|
||||
|
||||
async def clickhouse_get_span_raw(span_id: str) -> dict:
|
||||
"""Get raw span data from ClickHouse"""
|
||||
client = await get_async_clickhouse()
|
||||
query = """
|
||||
SELECT * FROM {table_name}
|
||||
WHERE SpanId = '{span_id}'
|
||||
"""
|
||||
query = query.format(table_name=IMPORT_TABLE_NAME, span_id=span_id)
|
||||
result = await client.query(query)
|
||||
if result and hasattr(result, 'result_rows') and len(result.result_rows) > 0:
|
||||
row_dict = dict(zip(result.column_names, result.result_rows[0]))
|
||||
return row_dict
|
||||
|
||||
return None
|
||||
|
||||
|
||||
async def clickhouse_create_span(span: Span) -> None:
|
||||
"""Create a single span in ClickHouse"""
|
||||
data = [span.to_clickhouse_dict()]
|
||||
await clickhouse_create(data)
|
||||
|
||||
|
||||
async def clickhouse_delete_span(span_id: Any) -> None:
|
||||
"""Delete a span from ClickHouse by SpanId"""
|
||||
client = await get_async_clickhouse()
|
||||
query = """
|
||||
ALTER TABLE {table_name}
|
||||
DELETE WHERE SpanId = '{span_id}'
|
||||
"""
|
||||
query = query.format(table_name=IMPORT_TABLE_NAME, span_id=str(span_id))
|
||||
if not DRY_RUN:
|
||||
await client.query(query)
|
||||
else:
|
||||
print(query)
|
||||
|
||||
|
||||
async def clickhouse_update_span(span_id: str, update_data: dict) -> None:
|
||||
"""Update a record in ClickHouse by deleting and re-inserting it."""
|
||||
# reasons for going this route at the moment:
|
||||
# - serialization is a bitch and there is no tooling readily available to help with it
|
||||
# - latency for propagation of updates is apparently comparable to deletion
|
||||
|
||||
def merge_dicts_recursive(old, new):
|
||||
result = old.copy()
|
||||
for key, value in new.items():
|
||||
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
|
||||
result[key] = merge_dicts_recursive(result[key], value)
|
||||
else:
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
existing_span: dict = await clickhouse_get_span_raw(span_id)
|
||||
if existing_span:
|
||||
await clickhouse_delete_span(span_id) # yolo
|
||||
else:
|
||||
existing_span = {}
|
||||
|
||||
merged_data = merge_dicts_recursive(existing_span, update_data)
|
||||
await clickhouse_create(
|
||||
[
|
||||
merged_data,
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
async def write_trace_with_timeout(trace: Trace) -> None:
|
||||
"""Write a trace to ClickHouse with a timeout"""
|
||||
try:
|
||||
write_task = asyncio.create_task(clickhouse_create_trace(trace))
|
||||
await asyncio.wait_for(write_task, timeout=TIMEOUT)
|
||||
return True
|
||||
except asyncio.TimeoutError:
|
||||
write_dropped_record('trace', trace.id, "Timeout")
|
||||
return False
|
||||
except Exception as e:
|
||||
write_dropped_record('trace', trace.id, str(e))
|
||||
return False
|
||||
|
||||
|
||||
async def process_page(offset: int, limit: int) -> None:
|
||||
"""Process a page of sessions and write them to ClickHouse"""
|
||||
pending_tasks = set()
|
||||
async for trace in get_sessions_as_traces(offset=offset, limit=limit):
|
||||
if len(pending_tasks) >= MAX_CONCURRENT:
|
||||
done, pending_tasks = await asyncio.wait(pending_tasks, return_when=asyncio.FIRST_COMPLETED)
|
||||
|
||||
for task in done:
|
||||
await task
|
||||
|
||||
task = asyncio.create_task(write_trace_with_timeout(trace))
|
||||
pending_tasks.add(task)
|
||||
|
||||
if pending_tasks: # let the pool drain
|
||||
done, pending = await asyncio.wait(pending_tasks)
|
||||
for task in done:
|
||||
await task
|
||||
await close_supabase_pool()
|
||||
|
||||
|
||||
async def count_session_rows() -> int:
|
||||
"""Count the number of rows in the sessions table"""
|
||||
query = """
|
||||
SELECT COUNT(*) FROM sessions
|
||||
WHERE id > '{last_session_id}'
|
||||
"""
|
||||
query = query.format(
|
||||
last_session_id=LAST_SESSION_ID if LAST_SESSION_ID else '00000000-0000-0000-0000-000000000000'
|
||||
)
|
||||
async with get_supabase_pool().connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
await cur.execute(query)
|
||||
rows = await cur.fetchone()
|
||||
return rows[0]
|
||||
|
||||
|
||||
def init_files():
|
||||
"""Initialize files needed for the exporter."""
|
||||
global _last_session_file, LAST_SESSION_ID
|
||||
|
||||
# Initialize dropped records file
|
||||
if not os.path.exists(DROPPED_RECORDS_FILENAME):
|
||||
with open(DROPPED_RECORDS_FILENAME, 'w') as f:
|
||||
f.write("table,id,exception\n")
|
||||
|
||||
# Initialize last session ID file
|
||||
if not os.path.exists(LAST_SESSION_ID_FILENAME):
|
||||
from pathlib import Path
|
||||
|
||||
Path(LAST_SESSION_ID_FILENAME).touch()
|
||||
|
||||
# Open the last session ID file
|
||||
_last_session_file = open(LAST_SESSION_ID_FILENAME, 'r+')
|
||||
LAST_SESSION_ID = _last_session_file.read().strip()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
"""Main entry point for the exporter"""
|
||||
# Initialize files
|
||||
init_files()
|
||||
|
||||
try:
|
||||
row_count = await count_session_rows()
|
||||
total_pages = row_count // BATCH_ROW_COUNT
|
||||
print(f"Total pages: {total_pages}".center(80, "="))
|
||||
|
||||
for page_number in range(0, total_pages):
|
||||
offset, limit = page_number * BATCH_ROW_COUNT, BATCH_ROW_COUNT
|
||||
await process_page(offset, limit)
|
||||
print(f"Processed page {page_number}".center(80, "="))
|
||||
if MAX_PAGES is not None and MAX_PAGES >= page_number:
|
||||
break
|
||||
finally:
|
||||
if _last_session_file:
|
||||
_last_session_file.close()
|
||||
await close_supabase_pool()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv('.env', override=True)
|
||||
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1 @@
|
||||
{"offset": 0, "total_processed": 0, "timestamp": "2025-04-02T18:32:28.613188"}
|
||||
@@ -0,0 +1,102 @@
|
||||
# Opsboard
|
||||
|
||||
The Opsboard module provides the backend API for user, organization, and project management in AgentOps. This module allows users to create and manage organizations, projects, and team members with role-based access controls.
|
||||
|
||||
## Architecture
|
||||
|
||||
Opsboard is a FastAPI application that serves REST API endpoints for the AgentOps dashboard. It uses:
|
||||
|
||||
- **FastAPI**: Web framework with automatic OpenAPI documentation
|
||||
- **SQLAlchemy ORM**: Database access and object-relational mapping
|
||||
- **Pydantic**: Data validation and serialization
|
||||
- **Authentication**: Uses the AgentOps auth module for secure user authentication
|
||||
|
||||
The module is structured to provide a clean separation of concerns:
|
||||
|
||||
```
|
||||
/opsboard
|
||||
├── app.py # FastAPI application setup and middleware
|
||||
├── environment.py # Environment-specific configuration
|
||||
├── models.py # SQLAlchemy ORM models
|
||||
├── routes.py # Route configuration and endpoint definitions
|
||||
├── schemas.py # Pydantic models for request/response validation
|
||||
└── views/ # Business logic and handlers
|
||||
├── users.py # User management endpoints
|
||||
├── orgs.py # Organization management endpoints
|
||||
└── projects.py # Project management endpoints
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
### User Management
|
||||
- User profile management
|
||||
- User preferences and settings
|
||||
- Survey completion tracking
|
||||
|
||||
### Organization Management
|
||||
- Create and manage organizations
|
||||
- Invite users to organizations
|
||||
- Role-based access control (owner, admin, developer, business_user)
|
||||
- Organization membership management
|
||||
|
||||
### Project Management
|
||||
- Create and manage projects within organizations
|
||||
- Project environment configuration (production, staging, development, community)
|
||||
- API key management for project access
|
||||
|
||||
## Models
|
||||
|
||||
The module uses the following primary data models:
|
||||
|
||||
- **UserModel**: User profile information
|
||||
- **OrgModel**: Organization details
|
||||
- **UserOrgModel**: User-organization relationships with roles
|
||||
- **OrgInviteModel**: Pending invitations to organizations
|
||||
- **ProjectModel**: Project configuration and API keys
|
||||
|
||||
## Authentication and Authorization
|
||||
|
||||
Opsboard uses the AgentOps auth module for authentication. All routes require authentication via the `AuthenticatedRoute` middleware. Authorization is managed through role-based permissions within the organization context.
|
||||
|
||||
## Endpoints
|
||||
|
||||
### User Endpoints
|
||||
- `GET /opsboard/users/me`: Get authenticated user profile
|
||||
- `POST /opsboard/users/update`: Update user profile
|
||||
- `POST /opsboard/users/complete_survey`: Mark user survey as complete
|
||||
|
||||
### Organization Endpoints
|
||||
- `GET /opsboard/orgs`: List organizations for the authenticated user
|
||||
- `GET /opsboard/orgs/{org_id}`: Get organization details
|
||||
- `POST /opsboard/orgs/create`: Create a new organization
|
||||
- `POST /opsboard/orgs/{org_id}/update`: Update organization details
|
||||
- `POST /opsboard/orgs/{org_id}/invite`: Invite a user to an organization
|
||||
- `GET /opsboard/orgs/invites`: List pending organization invites
|
||||
- `POST /opsboard/orgs/{org_id}/accept`: Accept an organization invitation
|
||||
- `POST /opsboard/orgs/{org_id}/members/remove`: Remove a user from an organization
|
||||
- `POST /opsboard/orgs/{org_id}/members/update`: Update a user's role in an organization
|
||||
- `DELETE /opsboard/orgs/{org_id}`: Delete an organization
|
||||
|
||||
### Project Endpoints
|
||||
- `GET /opsboard/projects`: List projects for the authenticated user
|
||||
- `GET /opsboard/projects/{project_id}`: Get project details
|
||||
- `POST /opsboard/projects`: Create a new project
|
||||
- `POST /opsboard/projects/{project_id}/update`: Update project details
|
||||
- `POST /opsboard/projects/{project_id}/delete`: Delete a project
|
||||
- `POST /opsboard/projects/{project_id}/regenerate-key`: Regenerate project API key
|
||||
|
||||
## Premium Status
|
||||
|
||||
Organizations can have different premium statuses that affect available features:
|
||||
- `free`: Basic features
|
||||
- `pro`: Advanced features
|
||||
- `enterprise`: Enterprise-level features and support
|
||||
|
||||
## Development
|
||||
|
||||
To run tests for the Opsboard module, use the project's test runner with the opsboard-specific tests:
|
||||
|
||||
```bash
|
||||
# From the root of the project
|
||||
pytest tests/opsboard/
|
||||
```
|
||||
@@ -0,0 +1,33 @@
|
||||
from fastapi import FastAPI, APIRouter
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from agentops.common.environment import ALLOWED_ORIGINS
|
||||
from agentops.common.middleware import (
|
||||
CacheControlMiddleware,
|
||||
DefaultContentTypeMiddleware,
|
||||
ExceptionMiddleware,
|
||||
)
|
||||
from agentops.common.route_config import register_routes
|
||||
from agentops.auth.middleware import AuthenticatedRoute
|
||||
|
||||
from .routes import route_config
|
||||
|
||||
__all__ = ["app"]
|
||||
|
||||
app = FastAPI(title="Opsboard API")
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=ALLOWED_ORIGINS,
|
||||
allow_credentials=True,
|
||||
allow_methods=["GET", "POST", "DELETE", "OPTIONS", "PUT"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.add_middleware(DefaultContentTypeMiddleware)
|
||||
app.add_middleware(CacheControlMiddleware)
|
||||
app.add_middleware(ExceptionMiddleware)
|
||||
|
||||
router = APIRouter(route_class=AuthenticatedRoute)
|
||||
register_routes(router, route_config, prefix="/opsboard")
|
||||
app.include_router(router)
|
||||
@@ -0,0 +1,15 @@
|
||||
from enum import Enum
|
||||
|
||||
|
||||
class BillingConstants:
|
||||
GRACE_PERIOD_DAYS = 3
|
||||
RACE_CONDITION_WINDOW_SECONDS = 5
|
||||
DEFAULT_SEAT_PRICE_CENTS = 4000
|
||||
|
||||
|
||||
class BillingAuditAction(str, Enum):
|
||||
MEMBER_LICENSED = "member_licensed"
|
||||
MEMBER_UNLICENSED = "member_unlicensed"
|
||||
LICENSES_SYNCED_BY_WEBHOOK = "licenses_synced_by_webhook"
|
||||
SUBSCRIPTION_CREATED = "subscription_created"
|
||||
SUBSCRIPTION_CANCELLED = "subscription_cancelled"
|
||||
@@ -0,0 +1 @@
|
||||
DEMO_ORG_ID = "c0000000-0000-0000-0000-000000000000"
|
||||
@@ -0,0 +1,819 @@
|
||||
"""
|
||||
SQLAlchemy models for the opsboard application.
|
||||
|
||||
NOTE: This is a subset of models migrated from the Supabase implementation.
|
||||
We're only implementing the core user and organization management features initially.
|
||||
"""
|
||||
|
||||
from typing import Optional, TYPE_CHECKING
|
||||
import enum
|
||||
from dataclasses import dataclass
|
||||
import uuid
|
||||
from uuid import UUID
|
||||
import sqlalchemy as model
|
||||
from sqlalchemy import orm
|
||||
from sqlalchemy.orm import joinedload, lazyload
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from agentops.common.environment import (
|
||||
FREEPLAN_MAX_USERS,
|
||||
FREEPLAN_MAX_PROJECTS,
|
||||
)
|
||||
from agentops.common.orm import BaseModel, require_loaded
|
||||
from .environment import DEMO_ORG_ID
|
||||
from sqlalchemy import func
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from agentops.api.auth import JWTPayload
|
||||
|
||||
|
||||
def normalize_uuid(id_: str | UUID) -> UUID:
|
||||
"""Normalize value to a UUID."""
|
||||
return uuid.UUID(id_) if isinstance(id_, str) else id_
|
||||
|
||||
|
||||
class OrgRoles(enum.Enum):
|
||||
"""Role types for organization members"""
|
||||
|
||||
# must match the database org_roles enum type (which is lowercase)
|
||||
owner = "owner"
|
||||
admin = "admin"
|
||||
developer = "developer"
|
||||
business_user = "business_user"
|
||||
|
||||
|
||||
class PremStatus(enum.Enum):
|
||||
"""Premium status types for organizations"""
|
||||
|
||||
# must match the database org_roles enum type (which is lowercase)
|
||||
free = "free"
|
||||
pro = "pro"
|
||||
enterprise = "enterprise"
|
||||
|
||||
|
||||
@dataclass
|
||||
class PremStatusAttributes:
|
||||
"""Attributes for each premium status"""
|
||||
|
||||
# `None` indicates there is no limit
|
||||
|
||||
max_users: int | None
|
||||
max_projects: int | None
|
||||
|
||||
|
||||
class Environment(enum.Enum):
|
||||
"""Environment types for projects"""
|
||||
|
||||
# must match the database org_roles enum type (which is lowercase)
|
||||
production = "production"
|
||||
staging = "staging"
|
||||
development = "development"
|
||||
community = "community"
|
||||
|
||||
|
||||
class AuthUserModel(BaseModel):
|
||||
"""
|
||||
Model representing Supabase's built-in auth.users table.
|
||||
|
||||
This model is provided for cases where auth.users access is absolutely necessary,
|
||||
as Supabase does not recommend we access it directly.
|
||||
|
||||
This model is read-only to prevent modification.
|
||||
"""
|
||||
|
||||
__tablename__ = "users"
|
||||
__table_args__ = {"schema": "auth"}
|
||||
__mapper_args__ = {"confirm_deleted_rows": False} # Make this model read-only
|
||||
|
||||
def __setattr__(self, name, value):
|
||||
"""Prevent modifications to auth.users table."""
|
||||
if hasattr(self, '_sa_instance_state') and self._sa_instance_state.persistent:
|
||||
raise RuntimeError("AuthUserModel is read-only. Do not modify auth.users table directly.")
|
||||
super().__setattr__(name, value)
|
||||
|
||||
id = model.Column(model.UUID, primary_key=True)
|
||||
email = model.Column(model.String, nullable=True)
|
||||
created_at = model.Column(model.DateTime(timezone=True), nullable=True)
|
||||
# there are additional columns in auth.users that we don't reference here
|
||||
|
||||
|
||||
class UserModel(BaseModel):
|
||||
"""User model that maps to the users table"""
|
||||
|
||||
__tablename__ = "users"
|
||||
__table_args__ = {"schema": "public"}
|
||||
|
||||
# For SQLAlchemy ORM, just use UUID primary key without trying to validate the foreign key
|
||||
# The actual foreign key constraint exists in the database already
|
||||
id = model.Column(model.UUID, primary_key=True)
|
||||
full_name = model.Column(model.String, nullable=True)
|
||||
avatar_url = model.Column(model.String, nullable=True)
|
||||
billing_address = model.Column(JSONB, nullable=True)
|
||||
payment_method = model.Column(JSONB, nullable=True)
|
||||
email = model.Column(model.String, default="", nullable=False)
|
||||
survey_is_complete = model.Column(model.Boolean, default=False, nullable=False)
|
||||
|
||||
orgs = orm.relationship("UserOrgModel", back_populates="user")
|
||||
invites = orm.relationship(
|
||||
"OrgInviteModel", foreign_keys="[OrgInviteModel.inviter_id]", back_populates="inviter_user"
|
||||
)
|
||||
auth_user = orm.relationship(
|
||||
"AuthUserModel",
|
||||
foreign_keys=[id],
|
||||
primaryjoin="UserModel.id == AuthUserModel.id",
|
||||
uselist=False,
|
||||
lazy="select", # Allow lazy loading for billing_email property
|
||||
)
|
||||
|
||||
def mark_survey_complete(self):
|
||||
self.survey_is_complete = True
|
||||
|
||||
@property
|
||||
def billing_email(self) -> str | None:
|
||||
"""Get the user's email from Supabase `auth.users` to ensure we use the canonical email."""
|
||||
# this performs a lazy load, but it's used infrequently so that's fine
|
||||
return self.auth_user.email if self.auth_user else None
|
||||
|
||||
@classmethod
|
||||
def get_by_id(cls, orm: orm.Session, user_id: str | UUID) -> Optional['UserModel']:
|
||||
"""Get a user by ID with relationships preloaded."""
|
||||
return (
|
||||
orm.query(cls)
|
||||
.options(
|
||||
joinedload(cls.orgs),
|
||||
joinedload(cls.invites),
|
||||
)
|
||||
.filter(cls.id == normalize_uuid(user_id))
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
class OrgModel(BaseModel):
|
||||
"""Organization model that maps to the orgs table"""
|
||||
|
||||
__tablename__ = "orgs"
|
||||
__table_args__ = {"schema": "public"}
|
||||
|
||||
id = model.Column(model.UUID, primary_key=True, default=uuid.uuid4)
|
||||
name = model.Column(model.String, nullable=False)
|
||||
prem_status = model.Column(model.Enum(PremStatus), default=PremStatus.free, nullable=False)
|
||||
subscription_id = model.Column(model.String, nullable=True)
|
||||
|
||||
users = orm.relationship("UserOrgModel", back_populates="org", cascade="all, delete-orphan")
|
||||
projects = orm.relationship("ProjectModel", back_populates="org")
|
||||
invites = orm.relationship("OrgInviteModel", back_populates="org", cascade="all, delete-orphan")
|
||||
|
||||
def set_current_user(self, user_id: str | UUID) -> None:
|
||||
"""
|
||||
Set the current user for this organization. THis is the user performing
|
||||
the request.
|
||||
|
||||
This allows us to access `current_user_role` as a property later.
|
||||
"""
|
||||
user_org = self.get_user_membership(user_id)
|
||||
self._current_user_role = user_org.role
|
||||
|
||||
@property
|
||||
def current_user_role(self) -> OrgRoles:
|
||||
"""Get the current user's role in this organization."""
|
||||
# this property helps us render this field in the response schema
|
||||
if not hasattr(self, "_current_user_role"):
|
||||
raise AttributeError("Current user role is not set. Call set_current_user() first.")
|
||||
|
||||
return self._current_user_role
|
||||
|
||||
@property
|
||||
def is_freeplan(self) -> bool:
|
||||
"""Check if the organization is on a free plan."""
|
||||
return self.prem_status == PremStatus.free
|
||||
|
||||
@property
|
||||
def current_member_count(self) -> int:
|
||||
"""The number of users that are a member of this organization."""
|
||||
# Use optimized count if available
|
||||
if hasattr(self, '_member_count'):
|
||||
return self._member_count
|
||||
# this includes the count of invites, too, so we can prevent the admin
|
||||
# from over-inviting users
|
||||
if not hasattr(self, 'users') or not hasattr(self, 'invites'):
|
||||
raise AttributeError(
|
||||
"Member count not available. Use get_by_id or get_all_for_user to load relationships."
|
||||
)
|
||||
return len(self.users) + len(self.invites)
|
||||
|
||||
@property
|
||||
def max_member_count(self) -> int | None:
|
||||
"""The maximum number of users that can be a member of this organization."""
|
||||
return FREEPLAN_MAX_USERS if self.is_freeplan else None
|
||||
|
||||
@property
|
||||
def current_project_count(self) -> int:
|
||||
"""The number of projects that are a member of this organization."""
|
||||
# Use optimized count if available
|
||||
if hasattr(self, '_project_count'):
|
||||
return self._project_count
|
||||
if not hasattr(self, 'projects'):
|
||||
raise AttributeError(
|
||||
"Project count not available. Use get_by_id or get_all_for_user to load relationships."
|
||||
)
|
||||
return len(self.projects)
|
||||
|
||||
@property
|
||||
def max_project_count(self) -> int | None:
|
||||
"""The maximum number of projects that can be a member of this organization."""
|
||||
return FREEPLAN_MAX_PROJECTS if self.is_freeplan else None
|
||||
|
||||
@property
|
||||
def paid_member_count(self) -> int:
|
||||
"""Get count of members marked as paid."""
|
||||
# Use cached value if available (set by get_by_id_summary)
|
||||
if hasattr(self, '_paid_member_count'):
|
||||
return self._paid_member_count
|
||||
|
||||
# If relationships are loaded, count only paid users
|
||||
if hasattr(self, 'users') and isinstance(self.users, list):
|
||||
return sum(1 for user_org in self.users if user_org.is_paid)
|
||||
|
||||
# Fallback to database query for paid users only
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
if self.id and hasattr(self, '_sa_instance_state'):
|
||||
orm = Session.object_session(self)
|
||||
if orm:
|
||||
return (
|
||||
orm.query(UserOrgModel)
|
||||
.filter(UserOrgModel.org_id == self.id, UserOrgModel.is_paid)
|
||||
.count()
|
||||
)
|
||||
|
||||
# Default fallback - at least the owner should be paid
|
||||
return 1
|
||||
|
||||
@property
|
||||
def unpaid_member_count(self) -> int:
|
||||
"""
|
||||
Get count of members not included in paid seats.
|
||||
This can be used in the future if we add granular control over who gets licensed
|
||||
"""
|
||||
if hasattr(self, 'users') and isinstance(self.users, list):
|
||||
return sum(1 for user_org in self.users if not user_org.is_paid)
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
if self.id and hasattr(self, '_sa_instance_state'):
|
||||
orm = Session.object_session(self)
|
||||
if orm:
|
||||
return (
|
||||
orm.query(UserOrgModel)
|
||||
.filter(UserOrgModel.org_id == self.id, ~UserOrgModel.is_paid)
|
||||
.count()
|
||||
)
|
||||
return 0
|
||||
|
||||
def create_user_membership(self, user_id: str | UUID, role: OrgRoles) -> 'UserOrgModel':
|
||||
"""Add a user to this organization with the given role."""
|
||||
|
||||
user_id = normalize_uuid(user_id)
|
||||
user_org = UserOrgModel(user_id=user_id, org_id=self.id, role=role)
|
||||
self.users.append(user_org)
|
||||
return user_org
|
||||
|
||||
@require_loaded('users')
|
||||
def get_user_membership(self, user_id: str | UUID) -> Optional['UserOrgModel']:
|
||||
"""Get a user's membership in this organization."""
|
||||
user_id = normalize_uuid(user_id)
|
||||
return next((user_org for user_org in self.users if user_org.user_id == user_id), None)
|
||||
|
||||
def is_user_member(self, user_id: str | UUID) -> bool:
|
||||
"""Check if a user is a member of this organization."""
|
||||
# If we have the current user role set from summary queries, use that
|
||||
if hasattr(self, '_current_user_role') and normalize_uuid(user_id) == normalize_uuid(
|
||||
getattr(self, '_current_user_id', user_id)
|
||||
):
|
||||
return True
|
||||
return self.get_user_membership(user_id) is not None
|
||||
|
||||
def is_user_admin_or_owner(self, user_id: str | UUID) -> bool:
|
||||
"""Check if a user is an admin or owner of this organization."""
|
||||
# If we have the current user role set from summary queries, use that
|
||||
if hasattr(self, '_current_user_role') and normalize_uuid(user_id) == normalize_uuid(
|
||||
getattr(self, '_current_user_id', user_id)
|
||||
):
|
||||
return self._current_user_role in [OrgRoles.owner, OrgRoles.admin]
|
||||
|
||||
if membership := self.get_user_membership(user_id):
|
||||
return membership.role in [OrgRoles.owner, OrgRoles.admin]
|
||||
|
||||
return False
|
||||
|
||||
def is_user_owner(self, user_id: str | UUID) -> bool:
|
||||
"""Check if a user is the owner of this organization."""
|
||||
# If we have the current user role set from summary queries, use that
|
||||
if hasattr(self, '_current_user_role') and normalize_uuid(user_id) == normalize_uuid(
|
||||
getattr(self, '_current_user_id', user_id)
|
||||
):
|
||||
return self._current_user_role == OrgRoles.owner
|
||||
|
||||
if membership := self.get_user_membership(user_id):
|
||||
return membership.role == OrgRoles.owner
|
||||
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def get_by_id(cls, orm: orm.Session, org_id: str | UUID) -> Optional['OrgModel']:
|
||||
"""Get an organization by ID with relationships preloaded."""
|
||||
return (
|
||||
orm.query(cls)
|
||||
.options(
|
||||
joinedload(cls.users),
|
||||
joinedload(cls.invites),
|
||||
joinedload(cls.projects),
|
||||
)
|
||||
.filter(cls.id == normalize_uuid(org_id))
|
||||
.first()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_all_for_user(cls, orm: orm.Session, user_id: str | UUID) -> Optional[list['OrgModel']]:
|
||||
"""Get all organizations for a user with relationships preloaded."""
|
||||
orgs = (
|
||||
orm.query(cls)
|
||||
.options(
|
||||
joinedload(cls.users),
|
||||
joinedload(cls.invites),
|
||||
joinedload(cls.projects),
|
||||
)
|
||||
.join(UserOrgModel, UserOrgModel.org_id == cls.id)
|
||||
.filter(UserOrgModel.user_id == normalize_uuid(user_id))
|
||||
.filter(cls.id != DEMO_ORG_ID) # TODO hard-code demo org and delete these rows
|
||||
.all()
|
||||
)
|
||||
for org in orgs:
|
||||
# populate current user so `org.current_user_role` is available
|
||||
org.set_current_user(user_id)
|
||||
return orgs
|
||||
|
||||
@classmethod
|
||||
def get_all_for_user_summary(cls, orm: orm.Session, user_id: str | UUID) -> list['OrgModel']:
|
||||
"""
|
||||
Get all organizations for a user with only summary data.
|
||||
|
||||
This method returns orgs with counts pre-calculated, avoiding the need
|
||||
to load all related records.
|
||||
"""
|
||||
from sqlalchemy import func
|
||||
|
||||
user_id = normalize_uuid(user_id)
|
||||
|
||||
# First, get all orgs for the user with their role
|
||||
orgs_with_roles = (
|
||||
orm.query(cls, UserOrgModel.role)
|
||||
.join(UserOrgModel, UserOrgModel.org_id == cls.id)
|
||||
.filter(UserOrgModel.user_id == user_id)
|
||||
.filter(cls.id != DEMO_ORG_ID)
|
||||
.all()
|
||||
)
|
||||
|
||||
if not orgs_with_roles:
|
||||
return []
|
||||
|
||||
# Extract org IDs for batch queries
|
||||
org_ids = [org.id for org, _ in orgs_with_roles]
|
||||
|
||||
# Batch query for user counts
|
||||
user_counts = dict(
|
||||
orm.query(UserOrgModel.org_id, func.count(UserOrgModel.user_id))
|
||||
.filter(UserOrgModel.org_id.in_(org_ids))
|
||||
.group_by(UserOrgModel.org_id)
|
||||
.all()
|
||||
)
|
||||
|
||||
# Batch query for invite counts
|
||||
invite_counts = dict(
|
||||
orm.query(OrgInviteModel.org_id, func.count(OrgInviteModel.invitee_email))
|
||||
.filter(OrgInviteModel.org_id.in_(org_ids))
|
||||
.group_by(OrgInviteModel.org_id)
|
||||
.all()
|
||||
)
|
||||
|
||||
# Batch query for project counts
|
||||
project_counts = dict(
|
||||
orm.query(ProjectModel.org_id, func.count(ProjectModel.id))
|
||||
.filter(ProjectModel.org_id.in_(org_ids))
|
||||
.group_by(ProjectModel.org_id)
|
||||
.all()
|
||||
)
|
||||
|
||||
# Assemble the results
|
||||
orgs = []
|
||||
for org, role in orgs_with_roles:
|
||||
# Set the current user role
|
||||
org._current_user_role = role
|
||||
org._current_user_id = user_id
|
||||
|
||||
# Get counts from batch results
|
||||
user_count = user_counts.get(org.id, 0)
|
||||
invite_count = invite_counts.get(org.id, 0)
|
||||
project_count = project_counts.get(org.id, 0)
|
||||
|
||||
# Store counts as private attributes
|
||||
org._member_count = user_count + invite_count
|
||||
org._user_count = user_count # Store user count separately for billing
|
||||
org._invite_count = invite_count # Store invite count separately
|
||||
org._project_count = project_count
|
||||
|
||||
orgs.append(org)
|
||||
|
||||
return orgs
|
||||
|
||||
@classmethod
|
||||
def get_by_id_summary(
|
||||
cls, orm: orm.Session, org_id: str | UUID, user_id: str | UUID
|
||||
) -> Optional['OrgModel']:
|
||||
"""
|
||||
Get an organization by ID with summary data only.
|
||||
Returns org with current user role but without loading all relationships.
|
||||
"""
|
||||
from sqlalchemy import func
|
||||
|
||||
org_id = normalize_uuid(org_id)
|
||||
user_id = normalize_uuid(user_id)
|
||||
|
||||
# Get org with user role
|
||||
result = (
|
||||
orm.query(cls, UserOrgModel.role)
|
||||
.join(UserOrgModel, (UserOrgModel.org_id == cls.id) & (UserOrgModel.user_id == user_id))
|
||||
.filter(cls.id == org_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
if result:
|
||||
org, role = result
|
||||
org._current_user_role = role
|
||||
org._current_user_id = user_id
|
||||
|
||||
# Calculate counts separately
|
||||
user_count = (
|
||||
orm.query(func.count(UserOrgModel.user_id)).filter(UserOrgModel.org_id == org.id).scalar()
|
||||
or 0
|
||||
)
|
||||
invite_count = (
|
||||
orm.query(func.count(OrgInviteModel.invitee_email))
|
||||
.filter(OrgInviteModel.org_id == org.id)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
project_count = (
|
||||
orm.query(func.count(ProjectModel.id)).filter(ProjectModel.org_id == org.id).scalar() or 0
|
||||
)
|
||||
|
||||
# Calculate paid member count separately
|
||||
paid_user_count = (
|
||||
orm.query(func.count(UserOrgModel.user_id))
|
||||
.filter(UserOrgModel.org_id == org.id, UserOrgModel.is_paid)
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
|
||||
org._member_count = user_count + invite_count
|
||||
org._user_count = user_count # Store user count separately for billing
|
||||
org._invite_count = invite_count # Store invite count separately
|
||||
org._project_count = project_count
|
||||
org._paid_member_count = paid_user_count # Store paid member count
|
||||
return org
|
||||
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def get_all_for_user_optimized(cls, orm: orm.Session, user_id: str | UUID) -> list['OrgModel']:
|
||||
"""Deprecated: Use get_all_for_user_summary instead."""
|
||||
return cls.get_all_for_user_summary(orm, user_id)
|
||||
|
||||
@classmethod
|
||||
def get_by_id_for_detail(cls, orm: orm.Session, org_id: str | UUID) -> Optional['OrgModel']:
|
||||
"""
|
||||
Get an organization by ID optimized for detail view.
|
||||
Only loads users (needed for detail view), not projects or invites.
|
||||
"""
|
||||
|
||||
org = (
|
||||
orm.query(cls)
|
||||
.options(
|
||||
joinedload(cls.users),
|
||||
# Use lazyload to prevent automatic loading but avoid errors
|
||||
lazyload(cls.projects),
|
||||
lazyload(cls.invites),
|
||||
)
|
||||
.filter(cls.id == normalize_uuid(org_id))
|
||||
.first()
|
||||
)
|
||||
|
||||
if org:
|
||||
# Calculate counts without loading all data
|
||||
from sqlalchemy import func
|
||||
|
||||
invite_count = (
|
||||
orm.query(func.count(OrgInviteModel.invitee_email))
|
||||
.filter(OrgInviteModel.org_id == org.id)
|
||||
.scalar()
|
||||
)
|
||||
project_count = (
|
||||
orm.query(func.count(ProjectModel.id)).filter(ProjectModel.org_id == org.id).scalar()
|
||||
)
|
||||
|
||||
org._member_count = len(org.users) + invite_count
|
||||
org._user_count = len(org.users) # Store user count separately for billing
|
||||
org._invite_count = invite_count # Store invite count separately
|
||||
org._project_count = project_count
|
||||
|
||||
return org
|
||||
|
||||
@classmethod
|
||||
def get_by_id_for_permission_check(
|
||||
cls, orm: orm.Session, org_id: str | UUID, user_id: str | UUID
|
||||
) -> Optional['OrgModel']:
|
||||
"""
|
||||
Get an organization by ID with only the current user's membership loaded.
|
||||
Optimized for permission checks - doesn't load all users/invites/projects.
|
||||
"""
|
||||
# Use the summary method which already handles this efficiently
|
||||
return cls.get_by_id_summary(orm, org_id, user_id)
|
||||
|
||||
|
||||
class UserOrgModel(BaseModel):
|
||||
"""Model that maps to the user_orgs table (many-to-many)"""
|
||||
|
||||
__tablename__ = "user_orgs"
|
||||
__table_args__ = {"schema": "public"}
|
||||
|
||||
user_id = model.Column(model.UUID, model.ForeignKey("public.users.id"), primary_key=True)
|
||||
org_id = model.Column(model.UUID, model.ForeignKey("public.orgs.id"), primary_key=True)
|
||||
role = model.Column(
|
||||
model.Enum(OrgRoles, name="org_roles", create_constraint=False, native_enum=True),
|
||||
default=OrgRoles.owner,
|
||||
)
|
||||
user_email = model.Column(model.String)
|
||||
is_paid = model.Column(model.Boolean, default=False)
|
||||
|
||||
user = orm.relationship("UserModel", back_populates="orgs")
|
||||
org = orm.relationship("OrgModel", back_populates="users")
|
||||
|
||||
|
||||
class OrgInviteModel(BaseModel):
|
||||
"""Model that maps to the org_invites table."""
|
||||
|
||||
__tablename__ = "org_invites"
|
||||
__table_args__ = {"schema": "public"}
|
||||
|
||||
inviter_id = model.Column(model.UUID, model.ForeignKey("public.users.id"), nullable=False)
|
||||
invitee_email = model.Column(model.String, primary_key=True)
|
||||
org_id = model.Column(model.UUID, model.ForeignKey("public.orgs.id"), primary_key=True)
|
||||
role = model.Column(
|
||||
model.Enum(OrgRoles, name="org_roles", create_constraint=False, native_enum=True),
|
||||
nullable=False,
|
||||
)
|
||||
org_name = model.Column(model.String, nullable=False)
|
||||
created_at = model.Column(model.DateTime(timezone=True), default=model.func.now())
|
||||
|
||||
inviter_user = orm.relationship("UserModel", foreign_keys=[inviter_id], back_populates="invites")
|
||||
org = orm.relationship("OrgModel", back_populates="invites")
|
||||
|
||||
|
||||
class SparseFieldException(ValueError):
|
||||
"""Exception raised when trying to access a field that is not available in the sparse model."""
|
||||
|
||||
def __init__(self, field_name: str):
|
||||
super().__init__(
|
||||
f"`{field_name}` is not available in sparse model. Call `get_project()` to load the full model."
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def raise_for_field(cls, field_name: str):
|
||||
raise cls(field_name)
|
||||
|
||||
|
||||
class BaseProjectModel:
|
||||
"""Base model for projects that defines common attributes and interface."""
|
||||
|
||||
is_sparse: bool
|
||||
id: UUID
|
||||
api_key: UUID
|
||||
|
||||
@property
|
||||
def is_freeplan(self) -> bool:
|
||||
"""Check if the project is on a free plan."""
|
||||
raise NotImplementedError("Subclasses must implement is_freeplan")
|
||||
|
||||
def get_project(self, orm: "orm.Session") -> Optional["ProjectModel"]:
|
||||
"""Get the full project model from the database."""
|
||||
raise NotImplementedError("Subclasses must implement get_project")
|
||||
|
||||
|
||||
class ProjectModel(BaseProjectModel, BaseModel):
|
||||
"""Model that maps to the projects table"""
|
||||
|
||||
__tablename__ = "projects"
|
||||
__table_args__ = {"schema": "public"}
|
||||
|
||||
is_sparse = False
|
||||
id = model.Column(model.UUID, primary_key=True, default=uuid.uuid4)
|
||||
org_id = model.Column(model.UUID, model.ForeignKey("public.orgs.id"), nullable=False)
|
||||
api_key = model.Column(model.UUID, unique=True, default=uuid.uuid4)
|
||||
name = model.Column(model.String, nullable=False)
|
||||
environment = model.Column(model.Enum(Environment), default=Environment.development, nullable=False)
|
||||
|
||||
org = orm.relationship("OrgModel", back_populates="projects")
|
||||
|
||||
@property
|
||||
@require_loaded('org')
|
||||
def is_freeplan(self) -> bool:
|
||||
"""Check if the organization is on a pro plan."""
|
||||
return self.org.is_freeplan
|
||||
|
||||
def get_project(self, orm: orm.Session) -> Optional["ProjectModel"]:
|
||||
"""For ProjectModel, return self since it's already the full model."""
|
||||
return self
|
||||
|
||||
@classmethod
|
||||
def get_by_id(cls, orm: orm.Session, project_id: str | UUID) -> Optional['ProjectModel']:
|
||||
"""Get a project by ID with org and necessary relationships preloaded."""
|
||||
# This loads org.users, org.invites, and org.projects relationships which are
|
||||
# needed when returning a `ProjectResponse` in these view functions:
|
||||
# - get_project
|
||||
# - create_project
|
||||
# - update_project
|
||||
# - regenerate_api_key
|
||||
# TODO: Consider optimizing with count queries instead of loading full relationships
|
||||
# when we only need counts for org.current_member_count and org.current_project_count.
|
||||
return (
|
||||
orm.query(cls)
|
||||
.filter(cls.id == normalize_uuid(project_id))
|
||||
.options(
|
||||
joinedload(cls.org).joinedload(OrgModel.users),
|
||||
joinedload(cls.org).joinedload(OrgModel.invites),
|
||||
joinedload(cls.org).joinedload(OrgModel.projects),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_by_api_key(cls, orm: orm.Session, api_key: str | UUID) -> Optional['ProjectModel']:
|
||||
"""Get a project by API key with org and necessary relationships preloaded."""
|
||||
return (
|
||||
orm.query(cls)
|
||||
.filter(cls.api_key == normalize_uuid(api_key))
|
||||
.options(
|
||||
joinedload(cls.org).joinedload(OrgModel.users),
|
||||
joinedload(cls.org).joinedload(OrgModel.invites),
|
||||
joinedload(cls.org).joinedload(OrgModel.projects),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def get_all_for_user(cls, orm: orm.Session, user_id: str | UUID) -> list['ProjectModel']:
|
||||
"""Get all projects the user has access to across all organizations they belong to."""
|
||||
projects = (
|
||||
orm.query(cls)
|
||||
.join(OrgModel, cls.org_id == OrgModel.id)
|
||||
.join(
|
||||
UserOrgModel,
|
||||
UserOrgModel.org_id == OrgModel.id,
|
||||
)
|
||||
.filter(UserOrgModel.user_id == normalize_uuid(user_id))
|
||||
.filter(OrgModel.id != DEMO_ORG_ID) # TODO hard-code demo org and delete these rows
|
||||
.options(
|
||||
joinedload(cls.org).joinedload(OrgModel.users),
|
||||
joinedload(cls.org).joinedload(OrgModel.invites),
|
||||
joinedload(cls.org).joinedload(OrgModel.projects),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
# Set the current user for each project's org
|
||||
for project in projects:
|
||||
project.org.set_current_user(user_id)
|
||||
|
||||
return projects
|
||||
|
||||
@classmethod
|
||||
def get_all_for_user_optimized(cls, orm: orm.Session, user_id: str | UUID) -> list['ProjectModel']:
|
||||
"""
|
||||
Get all projects the user has access to across all organizations they belong to.
|
||||
|
||||
Optimized version that only loads minimal data needed for project summaries.
|
||||
This avoids loading all users, invites, and projects for each organization.
|
||||
"""
|
||||
# Use a single query with minimal joins
|
||||
projects = (
|
||||
orm.query(cls)
|
||||
.join(OrgModel, cls.org_id == OrgModel.id)
|
||||
.join(UserOrgModel, UserOrgModel.org_id == OrgModel.id)
|
||||
.filter(UserOrgModel.user_id == normalize_uuid(user_id))
|
||||
.filter(OrgModel.id != DEMO_ORG_ID)
|
||||
.options(
|
||||
# Only load the org relationship itself, not all its relationships
|
||||
joinedload(cls.org),
|
||||
# Only load the specific user's membership for current_user_role
|
||||
joinedload(cls.org).joinedload(OrgModel.users).load_only(UserOrgModel.role),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
# Set the current user for each project's org with minimal overhead
|
||||
for project in projects:
|
||||
# Manually set the user's role without loading all org members
|
||||
user_org = next((uo for uo in project.org.users if uo.user_id == normalize_uuid(user_id)), None)
|
||||
if user_org:
|
||||
project.org._current_user_role = user_org.role
|
||||
|
||||
return projects
|
||||
|
||||
|
||||
class SparseProjectModel(BaseProjectModel):
|
||||
"""
|
||||
Sparse model for projects that is typically populated by a JWT token.
|
||||
|
||||
In contexts where we only need the cache fields available inside the JWT, this
|
||||
let's us save some db overhead and still reference a typed project object.
|
||||
"""
|
||||
|
||||
is_sparse = True
|
||||
org_id = property(lambda self: SparseFieldException.raise_for_field("org_id"))
|
||||
name = property(lambda self: SparseFieldException.raise_for_field("name"))
|
||||
environment = property(lambda self: SparseFieldException.raise_for_field("environment"))
|
||||
org = property(lambda self: SparseFieldException.raise_for_field("org"))
|
||||
_prem_status: PremStatus
|
||||
|
||||
def __init__(self, id: str | UUID, api_key: str | UUID, prem_status: str | PremStatus):
|
||||
self.id = normalize_uuid(id)
|
||||
self.api_key = normalize_uuid(api_key)
|
||||
self._prem_status = PremStatus(prem_status) if isinstance(prem_status, str) else prem_status
|
||||
|
||||
@property
|
||||
def is_freeplan(self) -> bool:
|
||||
"""Check if the project is on a free plan."""
|
||||
return self._prem_status == PremStatus.free
|
||||
|
||||
def get_project(self, orm: orm.Session) -> Optional[ProjectModel]:
|
||||
"""Get the full project model from the database."""
|
||||
return ProjectModel.get_by_id(orm, self.id)
|
||||
|
||||
@classmethod
|
||||
def from_auth_payload(cls, token: "JWTPayload") -> "SparseProjectModel":
|
||||
"""
|
||||
Create a SparseProjectModel from a JWT token.
|
||||
"""
|
||||
return cls(
|
||||
id=token.project_id,
|
||||
api_key=token.api_key,
|
||||
prem_status=token.project_prem_status,
|
||||
)
|
||||
|
||||
|
||||
class BillingAuditLog(BaseModel):
|
||||
__tablename__ = "billing_audit_logs"
|
||||
|
||||
id = model.Column(model.UUID, primary_key=True, default=uuid.uuid4)
|
||||
org_id = model.Column(model.UUID, model.ForeignKey("public.orgs.id"), nullable=False)
|
||||
user_id = model.Column(model.UUID, model.ForeignKey("public.users.id"), nullable=True)
|
||||
action = model.Column(
|
||||
model.String, nullable=False
|
||||
) # 'seats_updated', 'member_licensed', 'member_unlicensed'
|
||||
details = model.Column(model.JSON, nullable=False) # JSON with before/after values
|
||||
created_at = model.Column(model.DateTime, default=func.now())
|
||||
|
||||
|
||||
class WebhookEvent(BaseModel):
|
||||
"""Model for tracking processed webhook events to ensure idempotency"""
|
||||
|
||||
__tablename__ = "webhook_events"
|
||||
|
||||
event_id = model.Column(model.String, primary_key=True)
|
||||
processed_at = model.Column(model.DateTime, default=func.now())
|
||||
|
||||
|
||||
class BillingPeriod(BaseModel):
|
||||
"""Model for billing period snapshots used in dashboard"""
|
||||
|
||||
__tablename__ = "billing_periods"
|
||||
|
||||
id = model.Column(model.UUID, primary_key=True, default=uuid.uuid4)
|
||||
org_id = model.Column(model.UUID, model.ForeignKey("public.orgs.id"), nullable=False)
|
||||
period_start = model.Column(model.DateTime, nullable=False)
|
||||
period_end = model.Column(model.DateTime, nullable=False)
|
||||
stripe_invoice_id = model.Column(model.String(255), nullable=True)
|
||||
|
||||
# Costs breakdown (stored as cents)
|
||||
seat_cost = model.Column(model.Integer, nullable=False, default=0)
|
||||
seat_count = model.Column(model.Integer, nullable=False, default=0)
|
||||
|
||||
# Usage costs (JSON for extensibility)
|
||||
usage_costs = model.Column(JSONB, nullable=False, default={}) # {"tokens": 1500, "spans": 2000}
|
||||
usage_quantities = model.Column(JSONB, nullable=False, default={}) # {"tokens": 5000000, "spans": 125000}
|
||||
|
||||
total_cost = model.Column(model.Integer, nullable=False, default=0)
|
||||
status = model.Column(model.String(20), default='pending') # 'pending', 'invoiced', 'paid'
|
||||
invoiced_at = model.Column(model.DateTime, nullable=True)
|
||||
created_at = model.Column(model.DateTime, default=func.now())
|
||||
|
||||
__table_args__ = (model.UniqueConstraint('org_id', 'period_start', name='_org_period_uc'),)
|
||||
@@ -0,0 +1,249 @@
|
||||
from agentops.common.route_config import RouteConfig
|
||||
|
||||
from .views.users import (
|
||||
get_user,
|
||||
update_user,
|
||||
update_user_survey_complete,
|
||||
)
|
||||
|
||||
from .views.orgs import (
|
||||
get_user_orgs,
|
||||
get_org,
|
||||
create_org,
|
||||
update_org,
|
||||
invite_to_org,
|
||||
get_org_invites,
|
||||
get_org_invites_for_org,
|
||||
accept_org_invite,
|
||||
remove_from_org,
|
||||
change_member_role,
|
||||
delete_org,
|
||||
revoke_org_invite,
|
||||
create_checkout_session,
|
||||
create_free_subscription,
|
||||
validate_discount_code,
|
||||
cancel_subscription,
|
||||
reactivate_subscription,
|
||||
update_subscription,
|
||||
create_customer_portal_session,
|
||||
update_member_licenses,
|
||||
get_stripe_pricing,
|
||||
get_subscription_detail,
|
||||
preview_member_add_cost,
|
||||
)
|
||||
|
||||
from .views.projects import (
|
||||
get_projects,
|
||||
get_project,
|
||||
create_project,
|
||||
update_project,
|
||||
delete_project,
|
||||
regenerate_api_key,
|
||||
)
|
||||
|
||||
from .views.billing import BillingDashboardView
|
||||
|
||||
route_config: list[RouteConfig] = [
|
||||
# User routes
|
||||
RouteConfig(
|
||||
name='get_user',
|
||||
path="/users/me",
|
||||
endpoint=get_user,
|
||||
methods=["GET"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='update_user',
|
||||
path="/users/update",
|
||||
endpoint=update_user,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='update_user_survey_complete',
|
||||
path="/users/complete_survey",
|
||||
endpoint=update_user_survey_complete,
|
||||
methods=["POST"],
|
||||
),
|
||||
# Organization routes
|
||||
RouteConfig(
|
||||
name='get_user_orgs',
|
||||
path="/orgs",
|
||||
endpoint=get_user_orgs,
|
||||
methods=["GET"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='get_org_invites',
|
||||
path="/orgs/invites",
|
||||
endpoint=get_org_invites,
|
||||
methods=["GET"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='get_org_invites_for_org',
|
||||
path="/orgs/{org_id}/invites",
|
||||
endpoint=get_org_invites_for_org,
|
||||
methods=["GET"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='get_org',
|
||||
path="/orgs/{org_id}",
|
||||
endpoint=get_org,
|
||||
methods=["GET"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='create_org',
|
||||
path="/orgs/create",
|
||||
endpoint=create_org,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='update_org',
|
||||
path="/orgs/{org_id}/update",
|
||||
endpoint=update_org,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='invite_to_org',
|
||||
path="/orgs/{org_id}/invite",
|
||||
endpoint=invite_to_org,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='accept_org_invite',
|
||||
path="/orgs/{org_id}/accept",
|
||||
endpoint=accept_org_invite,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='remove_from_org',
|
||||
path="/orgs/{org_id}/members/remove",
|
||||
endpoint=remove_from_org,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='change_member_role',
|
||||
path="/orgs/{org_id}/members/update",
|
||||
endpoint=change_member_role,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='update_member_licenses',
|
||||
path="/orgs/{org_id}/members/licenses",
|
||||
endpoint=update_member_licenses,
|
||||
methods=["PUT"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='delete_org',
|
||||
path="/orgs/{org_id}",
|
||||
endpoint=delete_org,
|
||||
methods=["DELETE"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='create_checkout_session',
|
||||
path="/orgs/{org_id}/create-checkout-session",
|
||||
endpoint=create_checkout_session,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='create_free_subscription',
|
||||
path="/orgs/{org_id}/create-free-subscription",
|
||||
endpoint=create_free_subscription,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='validate_discount_code',
|
||||
path="/orgs/{org_id}/validate-discount-code",
|
||||
endpoint=validate_discount_code,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='cancel_subscription',
|
||||
path="/orgs/{org_id}/cancel-subscription",
|
||||
endpoint=cancel_subscription,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='reactivate_subscription',
|
||||
path="/orgs/{org_id}/reactivate-subscription",
|
||||
endpoint=reactivate_subscription,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='get_subscription_detail',
|
||||
path="/orgs/{org_id}/subscription-detail",
|
||||
endpoint=get_subscription_detail,
|
||||
methods=["GET"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='update_subscription',
|
||||
path="/orgs/{org_id}/update-subscription",
|
||||
endpoint=update_subscription,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='create_customer_portal_session',
|
||||
path="/orgs/{org_id}/customer-portal",
|
||||
endpoint=create_customer_portal_session,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='get_stripe_pricing',
|
||||
path="/orgs/{org_id}/stripe-pricing",
|
||||
endpoint=get_stripe_pricing,
|
||||
methods=["GET"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='preview_member_add_cost',
|
||||
path="/orgs/{org_id}/preview-member-cost",
|
||||
endpoint=preview_member_add_cost,
|
||||
methods=["GET"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='revoke_org_invite',
|
||||
path="/orgs/{org_id}/invites/{email}",
|
||||
endpoint=revoke_org_invite,
|
||||
methods=["DELETE"],
|
||||
),
|
||||
# Project routes
|
||||
RouteConfig(
|
||||
name='get_projects',
|
||||
path="/projects",
|
||||
endpoint=get_projects,
|
||||
methods=["GET"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='get_project',
|
||||
path="/projects/{project_id}",
|
||||
endpoint=get_project,
|
||||
methods=["GET"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='create_project',
|
||||
path="/projects",
|
||||
endpoint=create_project,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='update_project',
|
||||
path="/projects/{project_id}/update",
|
||||
endpoint=update_project,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='delete_project',
|
||||
path="/projects/{project_id}/delete",
|
||||
endpoint=delete_project,
|
||||
methods=["POST"],
|
||||
),
|
||||
RouteConfig(
|
||||
name='regenerate_api_key',
|
||||
path="/projects/{project_id}/regenerate-key",
|
||||
endpoint=regenerate_api_key,
|
||||
methods=["POST"],
|
||||
),
|
||||
# Billing routes
|
||||
RouteConfig(
|
||||
name='get_billing_dashboard',
|
||||
path="/orgs/{org_id}/billing/dashboard",
|
||||
endpoint=BillingDashboardView,
|
||||
methods=["GET"],
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,354 @@
|
||||
import pydantic
|
||||
from enum import Enum
|
||||
from uuid import UUID
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def uuid_to_str(v) -> str:
|
||||
"""Convert UUID to string for Pydantic models."""
|
||||
if isinstance(v, UUID):
|
||||
return str(v)
|
||||
return v
|
||||
|
||||
|
||||
class BaseSchema(pydantic.BaseModel):
|
||||
"""
|
||||
Base schema type intended to be used for creating input schemas.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class BaseResponse(BaseSchema):
|
||||
"""
|
||||
Base response type intended to be directly populated by a sqlalchemy model.
|
||||
"""
|
||||
|
||||
model_config = pydantic.ConfigDict(
|
||||
from_attributes=True,
|
||||
)
|
||||
|
||||
|
||||
class StatusResponse(BaseResponse):
|
||||
"""
|
||||
Status response type intended to be used for simple success/failure responses.
|
||||
"""
|
||||
|
||||
success: bool = True
|
||||
message: str | None = None
|
||||
|
||||
|
||||
class UserResponse(BaseResponse):
|
||||
"""
|
||||
User response model.
|
||||
"""
|
||||
|
||||
id: str
|
||||
full_name: str | None
|
||||
avatar_url: str | None
|
||||
billing_address: dict | None
|
||||
payment_method: dict | None
|
||||
email: str | None
|
||||
survey_is_complete: bool | None
|
||||
|
||||
@pydantic.field_validator("id", mode="before")
|
||||
@classmethod
|
||||
def validate_uuid(cls, v):
|
||||
return uuid_to_str(v)
|
||||
|
||||
|
||||
class UserUpdateSchema(BaseSchema):
|
||||
"""
|
||||
User update schema.
|
||||
"""
|
||||
|
||||
full_name: str | None = None
|
||||
avatar_url: str | None = None
|
||||
billing_address: dict | None = None
|
||||
payment_method: dict | None = None
|
||||
email: str | None = None
|
||||
survey_is_complete: bool | None = None
|
||||
|
||||
|
||||
class UserOrgResponse(BaseResponse):
|
||||
"""
|
||||
User-organization relationship information including role.
|
||||
"""
|
||||
|
||||
user_id: str
|
||||
org_id: str
|
||||
role: str
|
||||
user_email: str | None
|
||||
is_paid: bool = False # Whether this member counts against paid seats
|
||||
|
||||
@pydantic.field_validator("user_id", "org_id", mode="before")
|
||||
@classmethod
|
||||
def validate_uuid(cls, v):
|
||||
return uuid_to_str(v)
|
||||
|
||||
|
||||
class OrgResponse(BaseResponse):
|
||||
"""
|
||||
Organization response model.
|
||||
This contains fields which live directly on the OrgModel.
|
||||
"""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
prem_status: str
|
||||
subscription_id: str | None = None
|
||||
subscription_end_date: int | None = None
|
||||
subscription_start_date: int | None = None
|
||||
subscription_cancel_at_period_end: bool | None = None
|
||||
current_user_role: str | None = None
|
||||
current_member_count: int | None = None
|
||||
max_member_count: int | None = None
|
||||
current_project_count: int | None = None
|
||||
max_project_count: int | None = None
|
||||
paid_member_count: Optional[int] = None
|
||||
|
||||
@pydantic.field_validator("id", mode="before")
|
||||
@classmethod
|
||||
def validate_uuid(cls, v):
|
||||
return uuid_to_str(v)
|
||||
|
||||
@pydantic.field_validator("current_user_role", mode="before")
|
||||
@classmethod
|
||||
def validate_current_user_role_enum(cls, v):
|
||||
"""Convert the role Enum to a string."""
|
||||
return v.value if isinstance(v, Enum) else v
|
||||
|
||||
@pydantic.field_validator("prem_status", mode="before")
|
||||
@classmethod
|
||||
def validate_prem_status_enum(cls, v):
|
||||
"""Convert the prem_status Enum to a string."""
|
||||
return v.value if isinstance(v, Enum) else v
|
||||
|
||||
|
||||
class OrgDetailResponse(OrgResponse):
|
||||
"""
|
||||
Detailed organization response that includes user information.
|
||||
Used for single organization view.
|
||||
"""
|
||||
|
||||
users: list[UserOrgResponse]
|
||||
|
||||
@pydantic.field_validator("users", mode="before")
|
||||
@classmethod
|
||||
def validate_users(cls, v):
|
||||
if not v:
|
||||
return []
|
||||
return v
|
||||
|
||||
|
||||
class OrgCreateSchema(BaseSchema):
|
||||
"""
|
||||
Schema for creating an organization.
|
||||
"""
|
||||
|
||||
name: str
|
||||
|
||||
|
||||
class OrgUpdateSchema(BaseSchema):
|
||||
"""
|
||||
Schema for updating an organization.
|
||||
"""
|
||||
|
||||
name: str
|
||||
|
||||
|
||||
class OrgInviteSchema(BaseSchema):
|
||||
"""
|
||||
Schema for inviting a user to an organization.
|
||||
Email is used to identify the user, and role specifies their permissions level.
|
||||
"""
|
||||
|
||||
email: str
|
||||
role: str
|
||||
|
||||
|
||||
class OrgInviteResponse(BaseResponse):
|
||||
"""
|
||||
Organization invite response model.
|
||||
"""
|
||||
|
||||
inviter_id: str
|
||||
invitee_email: str
|
||||
org_id: str
|
||||
role: str
|
||||
org_name: str
|
||||
created_at: str | None = None
|
||||
|
||||
@pydantic.field_validator("inviter_id", "org_id", mode="before")
|
||||
@classmethod
|
||||
def validate_uuid(cls, v):
|
||||
return uuid_to_str(v)
|
||||
|
||||
@pydantic.field_validator("created_at", mode="before")
|
||||
@classmethod
|
||||
def validate_created_at(cls, v):
|
||||
"""Convert datetime to string."""
|
||||
if v is None:
|
||||
return None
|
||||
return v.isoformat() if hasattr(v, 'isoformat') else str(v)
|
||||
|
||||
|
||||
class OrgInviteDetailResponse(BaseResponse):
|
||||
"""
|
||||
Detailed organization invite response model for organization admin view.
|
||||
Includes additional information like inviter email and user existence status.
|
||||
"""
|
||||
|
||||
invitee_email: str
|
||||
inviter_email: str
|
||||
role: str
|
||||
org_id: str
|
||||
org_name: str
|
||||
created_at: str | None = None
|
||||
user_exists: bool
|
||||
|
||||
@pydantic.field_validator("org_id", mode="before")
|
||||
@classmethod
|
||||
def validate_uuid(cls, v):
|
||||
return uuid_to_str(v)
|
||||
|
||||
@pydantic.field_validator("created_at", mode="before")
|
||||
@classmethod
|
||||
def validate_created_at(cls, v):
|
||||
"""Convert datetime to string."""
|
||||
if v is None:
|
||||
return None
|
||||
return v.isoformat() if hasattr(v, 'isoformat') else str(v)
|
||||
|
||||
|
||||
class OrgMemberRemoveSchema(BaseSchema):
|
||||
"""
|
||||
Schema for removing a user from an organization.
|
||||
"""
|
||||
|
||||
user_id: str
|
||||
|
||||
|
||||
class OrgMemberRoleSchema(BaseSchema):
|
||||
"""
|
||||
Schema for changing a user's role in an organization.
|
||||
"""
|
||||
|
||||
user_id: str
|
||||
role: str
|
||||
|
||||
|
||||
class ValidateDiscountCodeBody(BaseSchema):
|
||||
"""
|
||||
Schema for validating a discount code (promotion code or coupon ID).
|
||||
"""
|
||||
|
||||
discount_code: str
|
||||
|
||||
|
||||
class ValidateDiscountCodeResponse(BaseResponse):
|
||||
"""
|
||||
Response schema for discount code validation.
|
||||
"""
|
||||
|
||||
valid: bool
|
||||
discount_type: str | None = None # 'percent_off' or 'amount_off'
|
||||
discount_value: float | None = None # percentage or amount in cents
|
||||
discount_description: str | None = None
|
||||
currency: str | None = None # only for amount_off
|
||||
is_100_percent_off: bool = False # Explicit flag for 100% off discounts
|
||||
|
||||
|
||||
class CreateFreeSubscriptionResponse(BaseResponse):
|
||||
"""
|
||||
Response schema for free subscription creation.
|
||||
"""
|
||||
|
||||
message: str
|
||||
subscription_id: str
|
||||
org_id: str
|
||||
|
||||
|
||||
class OrgSummaryResponse(BaseResponse):
|
||||
"""
|
||||
Organization summary information for inclusion in other responses.
|
||||
"""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
prem_status: str
|
||||
current_user_role: str
|
||||
|
||||
@pydantic.field_validator("id", mode="before")
|
||||
@classmethod
|
||||
def validate_uuid(cls, v):
|
||||
return uuid_to_str(v)
|
||||
|
||||
@pydantic.field_validator("prem_status", mode="before")
|
||||
@classmethod
|
||||
def validate_prem_status_enum(cls, v):
|
||||
"""Convert the prem_status Enum to a string."""
|
||||
return v.value if isinstance(v, Enum) else v
|
||||
|
||||
@pydantic.field_validator("current_user_role", mode="before")
|
||||
@classmethod
|
||||
def validate_current_user_role_enum(cls, v):
|
||||
"""Convert the role Enum to a string."""
|
||||
return v.value if isinstance(v, Enum) else v
|
||||
|
||||
|
||||
class ProjectSummaryResponse(BaseResponse):
|
||||
"""
|
||||
Project response model for listing projects.
|
||||
"""
|
||||
|
||||
id: str
|
||||
name: str
|
||||
api_key: str
|
||||
org: OrgSummaryResponse
|
||||
span_count: int = 0
|
||||
trace_count: int = 0
|
||||
|
||||
@pydantic.field_validator("id", "api_key", mode="before")
|
||||
@classmethod
|
||||
def validate_uuid(cls, v):
|
||||
return uuid_to_str(v)
|
||||
|
||||
|
||||
class ProjectResponse(BaseResponse):
|
||||
"""
|
||||
Project response model.
|
||||
Basic project information including organization details.
|
||||
"""
|
||||
|
||||
id: str
|
||||
org_id: str
|
||||
name: str
|
||||
environment: str
|
||||
api_key: str
|
||||
org: OrgResponse
|
||||
|
||||
@pydantic.field_validator("id", "org_id", "api_key", mode="before")
|
||||
@classmethod
|
||||
def validate_uuid(cls, v):
|
||||
return uuid_to_str(v)
|
||||
|
||||
|
||||
class ProjectCreateSchema(BaseSchema):
|
||||
"""
|
||||
Schema for creating a project.
|
||||
"""
|
||||
|
||||
name: str
|
||||
org_id: str
|
||||
environment: str | None = None
|
||||
|
||||
|
||||
class ProjectUpdateSchema(BaseSchema):
|
||||
"""
|
||||
Schema for updating a project.
|
||||
Only name and environment can be updated.
|
||||
"""
|
||||
|
||||
name: str | None = None
|
||||
environment: str | None = None
|
||||
@@ -0,0 +1,709 @@
|
||||
import os
|
||||
import stripe
|
||||
import logging
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...common.usage_tracking import UsageType
|
||||
from ..models import OrgModel, BillingPeriod
|
||||
from ...api.db.clickhouse_client import get_clickhouse
|
||||
from ...api.environment import (
|
||||
STRIPE_SECRET_KEY,
|
||||
STRIPE_SUBSCRIPTION_PRICE_ID,
|
||||
STRIPE_TOKEN_PRICE_ID,
|
||||
STRIPE_SPAN_PRICE_ID,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BillingService:
|
||||
def __init__(self):
|
||||
# Validate and set Stripe configuration with detailed logging
|
||||
self._validate_stripe_config()
|
||||
stripe.api_key = STRIPE_SECRET_KEY
|
||||
self._pricing_cache: Optional[Dict] = None
|
||||
self._cache_timestamp: Optional[datetime] = None
|
||||
self._cache_duration = 3600 # Cache for 1 hour
|
||||
|
||||
self._usage_cache: Dict[str, tuple[Dict[str, int], datetime]] = {}
|
||||
self._usage_cache_ttl = 300 # 5 minutes for usage data
|
||||
|
||||
def _validate_stripe_config(self):
|
||||
"""Validate Stripe configuration and log detailed status"""
|
||||
logger.info("=== BillingService Stripe Validation ===")
|
||||
|
||||
# Check all required Stripe variables
|
||||
required_vars = {
|
||||
"STRIPE_SECRET_KEY": STRIPE_SECRET_KEY,
|
||||
"STRIPE_SUBSCRIPTION_PRICE_ID": STRIPE_SUBSCRIPTION_PRICE_ID,
|
||||
"STRIPE_TOKEN_PRICE_ID": STRIPE_TOKEN_PRICE_ID,
|
||||
"STRIPE_SPAN_PRICE_ID": STRIPE_SPAN_PRICE_ID,
|
||||
}
|
||||
|
||||
all_present = True
|
||||
for var_name, var_value in required_vars.items():
|
||||
if var_value:
|
||||
masked_value = f"{var_value[:8]}..." if len(var_value) > 8 else var_value
|
||||
logger.info(f"✓ {var_name}: {masked_value}")
|
||||
else:
|
||||
logger.error(f"✗ {var_name}: NOT FOUND - This will cause billing failures!")
|
||||
all_present = False
|
||||
|
||||
if all_present:
|
||||
logger.info("✓ All required Stripe variables present, attempting Stripe API test...")
|
||||
try:
|
||||
# Test Stripe API connectivity with a simple call
|
||||
if STRIPE_SECRET_KEY:
|
||||
stripe.api_key = STRIPE_SECRET_KEY
|
||||
# This is a lightweight test call
|
||||
stripe.Account.retrieve()
|
||||
logger.info("✓ Stripe API connection successful")
|
||||
else:
|
||||
logger.error("✗ Cannot test Stripe API - STRIPE_SECRET_KEY missing")
|
||||
except stripe.error.AuthenticationError as e:
|
||||
logger.error(f"✗ Stripe API authentication failed: {e}")
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"✗ Stripe API error: {e}")
|
||||
except Exception as e:
|
||||
logger.error(f"✗ Unexpected error testing Stripe API: {e}")
|
||||
else:
|
||||
logger.error("✗ Missing required Stripe variables - billing service will not work properly")
|
||||
|
||||
logger.info("=========================================")
|
||||
|
||||
def _should_refresh_cache(self) -> bool:
|
||||
if not self._pricing_cache or not self._cache_timestamp:
|
||||
return True
|
||||
return (datetime.now() - self._cache_timestamp).total_seconds() > self._cache_duration
|
||||
|
||||
def _extract_price_amount(self, price_object, price_id: str) -> Optional[float]:
|
||||
"""
|
||||
Extract price amount from Stripe price object handling all pricing models.
|
||||
Returns price in cents (float for micro-pricing) or None if no valid pricing found.
|
||||
|
||||
For micro-pricing (like $0.0001), Stripe uses unit_amount_decimal field.
|
||||
This method converts all pricing to cents for consistent handling.
|
||||
"""
|
||||
logger.info(
|
||||
f"Extracting price from {price_id}: "
|
||||
f"billing_scheme={getattr(price_object, 'billing_scheme', 'missing')}, "
|
||||
f"type={getattr(price_object, 'type', 'missing')}, "
|
||||
f"active={getattr(price_object, 'active', 'missing')}"
|
||||
)
|
||||
|
||||
# Log all available price-related attributes for debugging
|
||||
unit_amount = getattr(price_object, 'unit_amount', None)
|
||||
unit_amount_decimal = getattr(price_object, 'unit_amount_decimal', None)
|
||||
custom_unit_amount = getattr(price_object, 'custom_unit_amount', None)
|
||||
tiers = getattr(price_object, 'tiers', None)
|
||||
currency_options = getattr(price_object, 'currency_options', None)
|
||||
|
||||
logger.info(
|
||||
f"Price object attributes for {price_id}: "
|
||||
f"unit_amount={unit_amount}, "
|
||||
f"unit_amount_decimal={unit_amount_decimal}, "
|
||||
f"custom_unit_amount={custom_unit_amount is not None}, "
|
||||
f"tiers_count={len(tiers) if tiers else 0}, "
|
||||
f"currency_options={list(currency_options.keys()) if currency_options else []}"
|
||||
)
|
||||
|
||||
# 1. Check unit_amount_decimal FIRST for micro-pricing (like $0.0001, $0.0002)
|
||||
if unit_amount_decimal is not None:
|
||||
try:
|
||||
# Parse as string to avoid float precision issues
|
||||
decimal_str = str(unit_amount_decimal).strip()
|
||||
logger.info(f"Processing unit_amount_decimal: '{decimal_str}'")
|
||||
|
||||
# Convert to Decimal for precise calculations
|
||||
decimal_value = Decimal(decimal_str)
|
||||
|
||||
# For micro-pricing, unit_amount_decimal appears to already be in the correct scale
|
||||
# Dashboard shows $0.0002, API returns 0.02 -> this IS 0.02 cents
|
||||
# Dashboard shows $0.0001, API returns 0.01 -> this IS 0.01 cents
|
||||
# Dashboard shows $40.00, API returns 4000 -> this IS 4000 cents
|
||||
price_amount = float(decimal_value)
|
||||
|
||||
logger.info(f"Using unit_amount_decimal directly: {decimal_str} -> {price_amount} cents")
|
||||
return price_amount
|
||||
|
||||
except (ValueError, TypeError, InvalidOperation) as e:
|
||||
logger.warning(f"Failed to parse unit_amount_decimal '{unit_amount_decimal}': {e}")
|
||||
|
||||
# 2. Standard case: unit_amount (for regular pricing in cents)
|
||||
if unit_amount is not None and unit_amount > 0:
|
||||
logger.info(f"Using unit_amount: {unit_amount} cents")
|
||||
return float(unit_amount)
|
||||
|
||||
# 3. Check custom_unit_amount for variable pricing
|
||||
if custom_unit_amount is not None:
|
||||
if hasattr(custom_unit_amount, 'minimum') and custom_unit_amount.minimum is not None:
|
||||
logger.info(f"Using custom_unit_amount.minimum: {custom_unit_amount.minimum}")
|
||||
return float(custom_unit_amount.minimum)
|
||||
elif hasattr(custom_unit_amount, 'maximum') and custom_unit_amount.maximum is not None:
|
||||
logger.info(f"Using custom_unit_amount.maximum: {custom_unit_amount.maximum}")
|
||||
return float(custom_unit_amount.maximum)
|
||||
|
||||
# 4. Check tiered pricing
|
||||
if tiers and len(tiers) > 0:
|
||||
first_tier = tiers[0]
|
||||
logger.info(
|
||||
f"Checking first tier: {vars(first_tier) if hasattr(first_tier, '__dict__') else first_tier}"
|
||||
)
|
||||
|
||||
# Check first tier for unit_amount
|
||||
if hasattr(first_tier, 'unit_amount') and first_tier.unit_amount is not None:
|
||||
logger.info(f"Using first tier unit_amount: {first_tier.unit_amount}")
|
||||
return float(first_tier.unit_amount)
|
||||
# Check first tier for unit_amount_decimal
|
||||
elif hasattr(first_tier, 'unit_amount_decimal') and first_tier.unit_amount_decimal is not None:
|
||||
try:
|
||||
decimal_value = Decimal(str(first_tier.unit_amount_decimal))
|
||||
price_amount = float(decimal_value * 100)
|
||||
logger.info(
|
||||
f"Using first tier unit_amount_decimal: {first_tier.unit_amount_decimal} -> {price_amount} cents"
|
||||
)
|
||||
return price_amount
|
||||
except (ValueError, TypeError, InvalidOperation) as e:
|
||||
logger.warning(f"Failed to parse tier unit_amount_decimal: {e}")
|
||||
# Check first tier for flat_amount
|
||||
elif hasattr(first_tier, 'flat_amount') and first_tier.flat_amount is not None:
|
||||
logger.info(f"Using first tier flat_amount: {first_tier.flat_amount}")
|
||||
return float(first_tier.flat_amount)
|
||||
|
||||
# 5. Check currency_options for multi-currency prices
|
||||
if currency_options:
|
||||
# Try USD first, then any available currency
|
||||
currencies_to_try = ['usd'] + [c for c in currency_options.keys() if c != 'usd']
|
||||
for currency in currencies_to_try:
|
||||
if currency in currency_options:
|
||||
options = currency_options[currency]
|
||||
logger.info(
|
||||
f"Checking currency_options[{currency}]: {vars(options) if hasattr(options, '__dict__') else options}"
|
||||
)
|
||||
|
||||
# Check unit_amount_decimal first
|
||||
if hasattr(options, 'unit_amount_decimal') and options.unit_amount_decimal is not None:
|
||||
try:
|
||||
decimal_value = Decimal(str(options.unit_amount_decimal))
|
||||
price_amount = float(decimal_value * 100)
|
||||
logger.info(
|
||||
f"Using currency_options[{currency}].unit_amount_decimal: {options.unit_amount_decimal} -> {price_amount} cents"
|
||||
)
|
||||
return price_amount
|
||||
except (ValueError, TypeError, InvalidOperation) as e:
|
||||
logger.warning(f"Failed to parse currency option unit_amount_decimal: {e}")
|
||||
|
||||
# Check unit_amount
|
||||
if hasattr(options, 'unit_amount') and options.unit_amount is not None:
|
||||
logger.info(f"Using currency_options[{currency}].unit_amount: {options.unit_amount}")
|
||||
return float(options.unit_amount)
|
||||
|
||||
logger.warning(
|
||||
f"No valid pricing amount found for {price_id}. "
|
||||
f"unit_amount={unit_amount}, "
|
||||
f"unit_amount_decimal={unit_amount_decimal}, "
|
||||
f"custom_unit_amount={custom_unit_amount}, "
|
||||
f"tiers={len(tiers) if tiers else 0}, "
|
||||
f"currency_options={list(currency_options.keys()) if currency_options else []}"
|
||||
)
|
||||
return None
|
||||
|
||||
def get_usage_pricing(self) -> Dict[UsageType, Dict]:
|
||||
"""Fetch usage pricing from Stripe or return cached values"""
|
||||
if not self._should_refresh_cache():
|
||||
return self._pricing_cache
|
||||
|
||||
try:
|
||||
token_price_id = STRIPE_TOKEN_PRICE_ID
|
||||
span_price_id = STRIPE_SPAN_PRICE_ID
|
||||
|
||||
pricing = {}
|
||||
|
||||
if token_price_id:
|
||||
try:
|
||||
token_price = stripe.Price.retrieve(token_price_id, expand=['currency_options', 'tiers'])
|
||||
|
||||
# Add detailed logging for debugging price configuration
|
||||
logger.info(
|
||||
f"Retrieved token price {token_price_id}: type={getattr(token_price, 'type', 'unknown')}, "
|
||||
f"unit_amount={getattr(token_price, 'unit_amount', 'missing')}, "
|
||||
f"billing_scheme={getattr(token_price, 'billing_scheme', 'missing')}, "
|
||||
f"active={getattr(token_price, 'active', 'missing')}"
|
||||
)
|
||||
|
||||
price_amount = self._extract_price_amount(token_price, token_price_id)
|
||||
|
||||
if price_amount is not None:
|
||||
pricing[UsageType.TOKENS] = {
|
||||
'price_per_unit': Decimal(str(price_amount)) / 100,
|
||||
'unit_size': getattr(token_price.transform_quantity, 'divide_by', 1000)
|
||||
if hasattr(token_price, 'transform_quantity') and token_price.transform_quantity
|
||||
else 1000,
|
||||
'display_unit': 'thousand tokens',
|
||||
'stripe_price_id': token_price_id,
|
||||
}
|
||||
logger.info(
|
||||
f"Token pricing configured: ${price_amount / 100:.4f} per {pricing[UsageType.TOKENS]['unit_size']} tokens"
|
||||
)
|
||||
else:
|
||||
logger.error(f"Token price {token_price_id} has no valid pricing amount")
|
||||
raise ValueError("Token price has no valid pricing amount")
|
||||
|
||||
except (stripe.error.StripeError, ValueError, TypeError, AttributeError) as e:
|
||||
logger.warning(f"Failed to retrieve token price {token_price_id}: {e}, using default")
|
||||
pricing[UsageType.TOKENS] = {
|
||||
'price_per_unit': Decimal("0.0002"), # $0.0002 per 1000 tokens
|
||||
'unit_size': 1000,
|
||||
'display_unit': 'thousand tokens',
|
||||
}
|
||||
else:
|
||||
logger.info("No STRIPE_TOKEN_PRICE_ID configured, using default token pricing")
|
||||
pricing[UsageType.TOKENS] = {
|
||||
'price_per_unit': Decimal("0.0002"), # $0.0002 per 1000 tokens
|
||||
'unit_size': 1000,
|
||||
'display_unit': 'thousand tokens',
|
||||
}
|
||||
|
||||
if span_price_id:
|
||||
try:
|
||||
span_price = stripe.Price.retrieve(span_price_id, expand=['currency_options', 'tiers'])
|
||||
|
||||
# Add detailed logging for debugging price configuration
|
||||
logger.info(
|
||||
f"Retrieved span price {span_price_id}: type={getattr(span_price, 'type', 'unknown')}, "
|
||||
f"unit_amount={getattr(span_price, 'unit_amount', 'missing')}, "
|
||||
f"billing_scheme={getattr(span_price, 'billing_scheme', 'missing')}, "
|
||||
f"active={getattr(span_price, 'active', 'missing')}"
|
||||
)
|
||||
|
||||
price_amount = self._extract_price_amount(span_price, span_price_id)
|
||||
|
||||
if price_amount is not None:
|
||||
pricing[UsageType.SPANS] = {
|
||||
'price_per_unit': Decimal(str(price_amount)) / 100,
|
||||
'unit_size': getattr(span_price.transform_quantity, 'divide_by', 1000)
|
||||
if hasattr(span_price, 'transform_quantity') and span_price.transform_quantity
|
||||
else 1000,
|
||||
'display_unit': 'thousand spans',
|
||||
'stripe_price_id': span_price_id,
|
||||
}
|
||||
logger.info(
|
||||
f"Span pricing configured: ${price_amount / 100:.4f} per {pricing[UsageType.SPANS]['unit_size']} spans"
|
||||
)
|
||||
else:
|
||||
logger.error(f"Span price {span_price_id} has no valid pricing amount")
|
||||
raise ValueError("Span price has no valid pricing amount")
|
||||
|
||||
except (stripe.error.StripeError, ValueError, TypeError, AttributeError) as e:
|
||||
logger.warning(f"Failed to retrieve span price {span_price_id}: {e}, using default")
|
||||
pricing[UsageType.SPANS] = {
|
||||
'price_per_unit': Decimal("0.0001"), # $0.0001 per 1000 spans
|
||||
'unit_size': 1000,
|
||||
'display_unit': 'thousand spans',
|
||||
}
|
||||
else:
|
||||
logger.info("No STRIPE_SPAN_PRICE_ID configured, using default span pricing")
|
||||
pricing[UsageType.SPANS] = {
|
||||
'price_per_unit': Decimal("0.0001"), # $0.0001 per 1000 spans
|
||||
'unit_size': 1000,
|
||||
'display_unit': 'thousand spans',
|
||||
}
|
||||
|
||||
self._pricing_cache = pricing
|
||||
self._cache_timestamp = datetime.now()
|
||||
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"Failed to fetch pricing from Stripe: {e}")
|
||||
return {
|
||||
UsageType.TOKENS: {
|
||||
'price_per_unit': Decimal("0.0002"), # $0.0002 per 1000 tokens
|
||||
'unit_size': 1000,
|
||||
'display_unit': 'thousand tokens',
|
||||
},
|
||||
UsageType.SPANS: {
|
||||
'price_per_unit': Decimal("0.0001"), # $0.0001 per 1000 spans
|
||||
'unit_size': 1000,
|
||||
'display_unit': 'thousand spans',
|
||||
},
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"Unexpected error in get_usage_pricing: {e}")
|
||||
return {
|
||||
UsageType.TOKENS: {
|
||||
'price_per_unit': Decimal("0.0002"), # $0.0002 per 1000 tokens
|
||||
'unit_size': 1000,
|
||||
'display_unit': 'thousand tokens',
|
||||
},
|
||||
UsageType.SPANS: {
|
||||
'price_per_unit': Decimal("0.0001"), # $0.0001 per 1000 spans
|
||||
'unit_size': 1000,
|
||||
'display_unit': 'thousand spans',
|
||||
},
|
||||
}
|
||||
|
||||
return self._pricing_cache
|
||||
|
||||
def get_seat_price(self) -> int:
|
||||
"""Get per-seat price in cents from Stripe or environment"""
|
||||
try:
|
||||
main_price_id = STRIPE_SUBSCRIPTION_PRICE_ID
|
||||
if main_price_id:
|
||||
price = stripe.Price.retrieve(main_price_id, expand=['currency_options', 'tiers'])
|
||||
if price.recurring and price.recurring.usage_type == 'licensed':
|
||||
price_amount = self._extract_price_amount(price, main_price_id)
|
||||
if price_amount is not None:
|
||||
# Convert float to int for seat pricing (seats should be whole cents)
|
||||
return int(round(price_amount))
|
||||
else:
|
||||
logger.warning(
|
||||
f"Seat price {main_price_id} has no valid pricing amount, falling back to default"
|
||||
)
|
||||
else:
|
||||
logger.warning(f"Seat price {main_price_id} is not configured for licensed usage")
|
||||
except stripe.error.StripeError as e:
|
||||
logger.error(f"Failed to fetch seat price from Stripe: {e}")
|
||||
except Exception as e:
|
||||
logger.error(f"Unexpected error fetching seat price: {e}")
|
||||
|
||||
return int(os.getenv("STRIPE_SEAT_PRICE_CENTS", "4000"))
|
||||
|
||||
async def get_usage_for_period(
|
||||
self,
|
||||
orm: Session,
|
||||
org_id: str,
|
||||
period_start: datetime,
|
||||
period_end: datetime,
|
||||
project_id: Optional[str] = None,
|
||||
) -> Dict[str, int]:
|
||||
"""Get usage quantities for a billing period by querying ClickHouse directly"""
|
||||
from ..models import ProjectModel
|
||||
|
||||
# Ensure we have timezone-aware datetimes
|
||||
if period_start.tzinfo is None:
|
||||
period_start = period_start.replace(tzinfo=timezone.utc)
|
||||
if period_end.tzinfo is None:
|
||||
period_end = period_end.replace(tzinfo=timezone.utc)
|
||||
|
||||
# Convert to UTC for consistent ClickHouse querying
|
||||
period_start_utc = period_start.astimezone(timezone.utc)
|
||||
period_end_utc = period_end.astimezone(timezone.utc)
|
||||
|
||||
# Validate that the period is reasonable (not more than 32 days for billing overview)
|
||||
period_duration = period_end_utc - period_start_utc
|
||||
if period_duration.days > 32:
|
||||
logger.warning(
|
||||
f"Billing period duration is {period_duration.days} days for org {org_id}, this may indicate a date scoping issue"
|
||||
)
|
||||
|
||||
cache_key = (
|
||||
f"{org_id}:{period_start_utc.isoformat()}:{period_end_utc.isoformat()}:{project_id or 'all'}"
|
||||
)
|
||||
if cache_key in self._usage_cache:
|
||||
cached_data, cached_time = self._usage_cache[cache_key]
|
||||
if (datetime.now() - cached_time).total_seconds() < self._usage_cache_ttl:
|
||||
logger.debug(f"Returning cached usage data for org {org_id}")
|
||||
return cached_data
|
||||
|
||||
# If project_id is specified, only query for that project
|
||||
if project_id:
|
||||
# Verify the project belongs to the org
|
||||
project = (
|
||||
orm.query(ProjectModel.id)
|
||||
.filter(ProjectModel.org_id == org_id, ProjectModel.id == project_id)
|
||||
.first()
|
||||
)
|
||||
if not project:
|
||||
empty_result = {}
|
||||
self._usage_cache[cache_key] = (empty_result, datetime.now())
|
||||
return empty_result
|
||||
project_ids = [project_id]
|
||||
else:
|
||||
projects = orm.query(ProjectModel.id).filter(ProjectModel.org_id == org_id).all()
|
||||
project_ids = [str(p.id) for p in projects]
|
||||
|
||||
if not project_ids:
|
||||
empty_result = {}
|
||||
self._usage_cache[cache_key] = (empty_result, datetime.now())
|
||||
return empty_result
|
||||
|
||||
clickhouse_client = get_clickhouse()
|
||||
|
||||
try:
|
||||
usage_query = """
|
||||
SELECT
|
||||
COUNT(*) as span_count,
|
||||
SUM(
|
||||
COALESCE(
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.total_tokens'], '0')),
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.prompt_tokens'], '0')) +
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.completion_tokens'], '0')) +
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.cache_read_input_tokens'], '0')) +
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.reasoning_tokens'], '0'))
|
||||
)
|
||||
) as total_tokens
|
||||
FROM otel_2.otel_traces
|
||||
WHERE project_id IN %(project_ids)s
|
||||
AND Timestamp >= %(period_start)s
|
||||
AND Timestamp <= %(period_end)s
|
||||
"""
|
||||
|
||||
# Use timezone-aware formatting for ClickHouse (ClickHouse expects UTC)
|
||||
formatted_start = period_start_utc.strftime('%Y-%m-%d %H:%M:%S')
|
||||
formatted_end = period_end_utc.strftime('%Y-%m-%d %H:%M:%S')
|
||||
|
||||
logger.info(
|
||||
f"Querying usage for org {org_id} from {formatted_start} to {formatted_end} (project_ids: {project_ids})"
|
||||
)
|
||||
|
||||
result = clickhouse_client.query(
|
||||
usage_query,
|
||||
{
|
||||
'project_ids': project_ids,
|
||||
'period_start': formatted_start,
|
||||
'period_end': formatted_end,
|
||||
},
|
||||
)
|
||||
|
||||
if result.result_rows:
|
||||
span_count, total_tokens = result.result_rows[0]
|
||||
|
||||
logger.info(f"Usage data for org {org_id}: {total_tokens} total tokens, {span_count} spans")
|
||||
else:
|
||||
span_count, total_tokens = 0, 0
|
||||
logger.info(
|
||||
f"No usage data found for org {org_id} in period {formatted_start} to {formatted_end}"
|
||||
)
|
||||
|
||||
usage_data = {
|
||||
'tokens': int(total_tokens) if total_tokens else 0,
|
||||
'spans': int(span_count) if span_count else 0,
|
||||
}
|
||||
|
||||
logger.info(
|
||||
f"Final usage data for org {org_id}: {usage_data['tokens']} tokens and {usage_data['spans']} spans"
|
||||
)
|
||||
|
||||
self._usage_cache[cache_key] = (usage_data, datetime.now())
|
||||
|
||||
if len(self._usage_cache) > 100:
|
||||
current_time = datetime.now()
|
||||
expired_keys = [
|
||||
k
|
||||
for k, (_, cached_time) in self._usage_cache.items()
|
||||
if (current_time - cached_time).total_seconds() > self._usage_cache_ttl
|
||||
]
|
||||
for key in expired_keys:
|
||||
del self._usage_cache[key]
|
||||
|
||||
return usage_data
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error querying usage data for org {org_id}: {e}")
|
||||
return {}
|
||||
|
||||
async def get_usage_by_project_for_period(
|
||||
self, orm: Session, org_id: str, period_start: datetime, period_end: datetime
|
||||
) -> Dict[str, Dict[str, int]]:
|
||||
"""Get usage quantities for a billing period broken down by project"""
|
||||
from ..models import ProjectModel
|
||||
|
||||
# Ensure we have timezone-aware datetimes
|
||||
if period_start.tzinfo is None:
|
||||
period_start = period_start.replace(tzinfo=timezone.utc)
|
||||
if period_end.tzinfo is None:
|
||||
period_end = period_end.replace(tzinfo=timezone.utc)
|
||||
|
||||
# Convert to UTC for consistent ClickHouse querying
|
||||
period_start_utc = period_start.astimezone(timezone.utc)
|
||||
period_end_utc = period_end.astimezone(timezone.utc)
|
||||
|
||||
projects = orm.query(ProjectModel.id, ProjectModel.name).filter(ProjectModel.org_id == org_id).all()
|
||||
project_ids = [str(p.id) for p in projects]
|
||||
project_names = {str(p.id): p.name for p in projects}
|
||||
|
||||
if not project_ids:
|
||||
return {}
|
||||
|
||||
clickhouse_client = get_clickhouse()
|
||||
|
||||
try:
|
||||
# Same query as get_usage_for_period but grouped by project_id
|
||||
usage_query = """
|
||||
SELECT
|
||||
project_id,
|
||||
COUNT(*) as span_count,
|
||||
SUM(
|
||||
COALESCE(
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.total_tokens'], '0')),
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.prompt_tokens'], '0')) +
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.completion_tokens'], '0')) +
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.cache_read_input_tokens'], '0')) +
|
||||
toUInt64OrZero(ifNull(SpanAttributes['gen_ai.usage.reasoning_tokens'], '0'))
|
||||
)
|
||||
) as total_tokens
|
||||
FROM otel_2.otel_traces
|
||||
WHERE project_id IN %(project_ids)s
|
||||
AND Timestamp >= %(period_start)s
|
||||
AND Timestamp <= %(period_end)s
|
||||
GROUP BY project_id
|
||||
"""
|
||||
|
||||
formatted_start = period_start_utc.strftime('%Y-%m-%d %H:%M:%S')
|
||||
formatted_end = period_end_utc.strftime('%Y-%m-%d %H:%M:%S')
|
||||
|
||||
logger.info(
|
||||
f"Querying per-project usage for org {org_id} from {formatted_start} to {formatted_end}"
|
||||
)
|
||||
|
||||
result = clickhouse_client.query(
|
||||
usage_query,
|
||||
{
|
||||
'project_ids': project_ids,
|
||||
'period_start': formatted_start,
|
||||
'period_end': formatted_end,
|
||||
},
|
||||
)
|
||||
|
||||
project_usage = {}
|
||||
|
||||
for row in result.result_rows:
|
||||
project_id, span_count, total_tokens = row
|
||||
|
||||
project_usage[str(project_id)] = {
|
||||
'tokens': int(total_tokens) if total_tokens else 0,
|
||||
'spans': int(span_count) if span_count else 0,
|
||||
'project_name': project_names.get(str(project_id), 'Unknown Project'),
|
||||
}
|
||||
|
||||
# Include projects with zero usage
|
||||
for project_id, project_name in project_names.items():
|
||||
if project_id not in project_usage:
|
||||
project_usage[project_id] = {
|
||||
'tokens': 0,
|
||||
'spans': 0,
|
||||
'project_name': project_name,
|
||||
}
|
||||
|
||||
logger.info(f"Found usage data for {len(project_usage)} projects in org {org_id}")
|
||||
return project_usage
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error querying per-project usage data for org {org_id}: {e}")
|
||||
return {}
|
||||
|
||||
async def calculate_usage_costs(self, usage_quantities: Dict[str, int]) -> Dict[str, int]:
|
||||
"""Calculate costs from usage quantities
|
||||
|
||||
For micro-pricing (like $0.0001, $0.0002), we enforce a minimum charge threshold
|
||||
to avoid charging customers $0.00. Costs are only included if they round to at least 1 cent.
|
||||
"""
|
||||
costs = {}
|
||||
pricing = self.get_usage_pricing()
|
||||
|
||||
for usage_type_str, quantity in usage_quantities.items():
|
||||
try:
|
||||
usage_type = UsageType(usage_type_str)
|
||||
if usage_type in pricing:
|
||||
price_config = pricing[usage_type]
|
||||
|
||||
units = Decimal(str(quantity)) / Decimal(str(price_config['unit_size']))
|
||||
cost_dollars = units * price_config['price_per_unit']
|
||||
cost_cents = cost_dollars * 100
|
||||
final_cost_cents = int(cost_cents.quantize(Decimal('1'), rounding='ROUND_HALF_UP'))
|
||||
|
||||
# Only include costs that are at least 1 cent to avoid $0.00 charges
|
||||
if final_cost_cents >= 1:
|
||||
costs[usage_type_str] = final_cost_cents
|
||||
logger.info(
|
||||
f"Usage cost for {usage_type_str}: {quantity} units -> {final_cost_cents} cents "
|
||||
f"(${cost_dollars:.6f})"
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
f"Usage cost for {usage_type_str}: {quantity} units -> {cost_cents:.6f} cents "
|
||||
f"(below 1 cent threshold, not charged)"
|
||||
)
|
||||
except (ValueError, TypeError, InvalidOperation) as e:
|
||||
logger.warning(
|
||||
f"Error calculating cost for usage type {usage_type_str} with quantity {quantity}: {e}"
|
||||
)
|
||||
continue
|
||||
except Exception as e:
|
||||
logger.error(f"Unexpected error calculating cost for usage type {usage_type_str}: {e}")
|
||||
continue
|
||||
|
||||
return costs
|
||||
|
||||
async def create_billing_period_snapshot(
|
||||
self, orm: Session, org: OrgModel, period_start: datetime, period_end: datetime
|
||||
) -> BillingPeriod:
|
||||
"""Create a billing snapshot for the period"""
|
||||
|
||||
seat_count = org.paid_member_count or 1
|
||||
seat_cost = seat_count * self.get_seat_price()
|
||||
|
||||
usage_quantities = await self.get_usage_for_period(orm, str(org.id), period_start, period_end)
|
||||
|
||||
usage_costs = await self.calculate_usage_costs(usage_quantities)
|
||||
|
||||
total_cost = seat_cost + sum(usage_costs.values())
|
||||
|
||||
billing_period = BillingPeriod(
|
||||
org_id=org.id,
|
||||
period_start=period_start,
|
||||
period_end=period_end,
|
||||
seat_cost=seat_cost,
|
||||
seat_count=seat_count,
|
||||
usage_costs=usage_costs,
|
||||
usage_quantities=usage_quantities,
|
||||
total_cost=total_cost,
|
||||
status='pending',
|
||||
)
|
||||
|
||||
orm.add(billing_period)
|
||||
orm.commit()
|
||||
|
||||
return billing_period
|
||||
|
||||
|
||||
billing_service = BillingService()
|
||||
|
||||
|
||||
# Log final validation summary when module is imported
|
||||
def _log_billing_service_ready():
|
||||
"""Log final status of billing service configuration"""
|
||||
logger.info("=== Billing Service Configuration Summary ===")
|
||||
|
||||
# Check if all required variables are present
|
||||
required_vars = [
|
||||
STRIPE_SECRET_KEY,
|
||||
STRIPE_SUBSCRIPTION_PRICE_ID,
|
||||
STRIPE_TOKEN_PRICE_ID,
|
||||
STRIPE_SPAN_PRICE_ID,
|
||||
]
|
||||
all_present = all(var for var in required_vars)
|
||||
|
||||
if all_present:
|
||||
logger.info("✓ All Stripe variables configured - Billing service ready for production")
|
||||
else:
|
||||
missing = [
|
||||
name
|
||||
for name, var in [
|
||||
("STRIPE_SECRET_KEY", STRIPE_SECRET_KEY),
|
||||
("STRIPE_SUBSCRIPTION_PRICE_ID", STRIPE_SUBSCRIPTION_PRICE_ID),
|
||||
("STRIPE_TOKEN_PRICE_ID", STRIPE_TOKEN_PRICE_ID),
|
||||
("STRIPE_SPAN_PRICE_ID", STRIPE_SPAN_PRICE_ID),
|
||||
]
|
||||
if not var
|
||||
]
|
||||
logger.error(f"✗ Billing service NOT ready - missing: {', '.join(missing)}")
|
||||
logger.error("This will cause billing operations to fail or use fallback values")
|
||||
|
||||
logger.info("============================================")
|
||||
|
||||
|
||||
# Call validation when module is imported
|
||||
_log_billing_service_ready()
|
||||
@@ -0,0 +1,46 @@
|
||||
from .users import get_user, update_user, update_user_survey_complete
|
||||
from .orgs import (
|
||||
get_user_orgs,
|
||||
get_org,
|
||||
create_org,
|
||||
update_org,
|
||||
invite_to_org,
|
||||
get_org_invites,
|
||||
accept_org_invite,
|
||||
remove_from_org,
|
||||
change_member_role,
|
||||
preview_member_add_cost,
|
||||
)
|
||||
from .projects import (
|
||||
get_projects,
|
||||
get_project,
|
||||
create_project,
|
||||
update_project,
|
||||
delete_project,
|
||||
regenerate_api_key,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
# User views
|
||||
'get_user',
|
||||
'update_user',
|
||||
'update_user_survey_complete',
|
||||
# Organization views
|
||||
'get_user_orgs',
|
||||
'get_org',
|
||||
'create_org',
|
||||
'update_org',
|
||||
'invite_to_org',
|
||||
'get_org_invites',
|
||||
'accept_org_invite',
|
||||
'remove_from_org',
|
||||
'change_member_role',
|
||||
'preview_member_add_cost',
|
||||
# Project views
|
||||
'get_projects',
|
||||
'get_project',
|
||||
'create_project',
|
||||
'update_project',
|
||||
'delete_project',
|
||||
'regenerate_api_key',
|
||||
]
|
||||
@@ -0,0 +1,430 @@
|
||||
from typing import List, Optional, Dict
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from pydantic import BaseModel, field_validator
|
||||
from fastapi import Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
import stripe
|
||||
import logging
|
||||
|
||||
from agentops.common.orm import get_orm_session
|
||||
from agentops.common.route_config import BaseView
|
||||
from agentops.common.views import add_cors_headers
|
||||
from agentops.common.environment import APP_URL
|
||||
from agentops.api.environment import STRIPE_SECRET_KEY, STRIPE_SUBSCRIPTION_PRICE_ID
|
||||
from ..models import OrgModel, BillingPeriod
|
||||
from ..services.billing_service import billing_service
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class UsageCostBreakdown(BaseModel):
|
||||
usage_type: str
|
||||
quantity: int
|
||||
cost_cents: int
|
||||
|
||||
|
||||
class BillingPeriodResponse(BaseModel):
|
||||
id: str
|
||||
period_start: str
|
||||
period_end: str
|
||||
seat_cost: int
|
||||
seat_count: int
|
||||
usage_costs: Dict[str, int]
|
||||
usage_quantities: Dict[str, int]
|
||||
usage_breakdown: List[UsageCostBreakdown]
|
||||
total_cost: int
|
||||
status: str
|
||||
|
||||
@field_validator('period_start', 'period_end', mode='before')
|
||||
def format_datetime(cls, v) -> str:
|
||||
"""Ensure datetime fields are formatted as ISO strings."""
|
||||
if isinstance(v, datetime):
|
||||
return v.isoformat()
|
||||
return v
|
||||
|
||||
|
||||
# costs are in cents
|
||||
class ProjectUsageBreakdown(BaseModel):
|
||||
project_id: str
|
||||
project_name: str
|
||||
tokens: int
|
||||
spans: int
|
||||
token_cost: int
|
||||
span_cost: int
|
||||
total_cost: int
|
||||
|
||||
|
||||
class BillingDashboardResponse(BaseModel):
|
||||
current_period: Optional[BillingPeriodResponse]
|
||||
past_periods: List[BillingPeriodResponse]
|
||||
total_spent_all_time: int
|
||||
is_legacy_billing: bool = False
|
||||
legacy_cancellation_date: Optional[str] = None
|
||||
project_breakdown: Optional[List[ProjectUsageBreakdown]] = None
|
||||
|
||||
@field_validator('legacy_cancellation_date', mode='before')
|
||||
def format_legacy_date(cls, v) -> Optional[str]:
|
||||
"""Format datetime as ISO string if present."""
|
||||
if isinstance(v, datetime):
|
||||
return v.isoformat()
|
||||
return v
|
||||
|
||||
|
||||
class BillingDashboardView(BaseView):
|
||||
"""Get billing dashboard data with cost breakdown"""
|
||||
|
||||
@add_cors_headers(
|
||||
origins=[APP_URL],
|
||||
methods=["GET", "OPTIONS"],
|
||||
)
|
||||
async def __call__(
|
||||
self,
|
||||
org_id: str,
|
||||
start_date: Optional[str] = Query(None, alias="start_date"),
|
||||
end_date: Optional[str] = Query(None, alias="end_date"),
|
||||
project_id: Optional[str] = Query(None, alias="project_id"),
|
||||
period: Optional[str] = Query(None, alias="period"), # For backward compatibility
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> BillingDashboardResponse:
|
||||
"""Get billing dashboard data with cost breakdown"""
|
||||
|
||||
# Handle FastAPI Query objects when called directly in tests
|
||||
|
||||
# Check for various FastAPI Query object types
|
||||
if hasattr(start_date, 'default') or str(type(start_date)).find('Query') != -1:
|
||||
logger.debug(f"Converting start_date Query object to None: {type(start_date)}")
|
||||
start_date = None
|
||||
if hasattr(end_date, 'default') or str(type(end_date)).find('Query') != -1:
|
||||
logger.debug(f"Converting end_date Query object to None: {type(end_date)}")
|
||||
end_date = None
|
||||
if hasattr(project_id, 'default') or str(type(project_id)).find('Query') != -1:
|
||||
logger.debug(f"Converting project_id Query object to None: {type(project_id)}")
|
||||
project_id = None
|
||||
if hasattr(period, 'default') or str(type(period)).find('Query') != -1:
|
||||
logger.debug(f"Converting period Query object to None: {type(period)}")
|
||||
period = None
|
||||
|
||||
logger.debug(
|
||||
f"Final parameter values: period={period}, start_date={start_date}, end_date={end_date}, project_id={project_id}"
|
||||
)
|
||||
|
||||
org = OrgModel.get_by_id_summary(orm, org_id, self.request.state.session.user_id)
|
||||
if not org or not org.is_user_member(self.request.state.session.user_id):
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
# Handle specific billing period if provided (backward compatibility)
|
||||
if period:
|
||||
try:
|
||||
billing_period = (
|
||||
orm.query(BillingPeriod)
|
||||
.filter(BillingPeriod.id == period, BillingPeriod.org_id == org_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
if not billing_period:
|
||||
raise HTTPException(status_code=404, detail="Billing period not found")
|
||||
|
||||
# Convert stored billing period to response format
|
||||
usage_breakdown = []
|
||||
for usage_type, quantity in billing_period.usage_quantities.items():
|
||||
cost = billing_period.usage_costs.get(usage_type, 0)
|
||||
usage_breakdown.append(
|
||||
UsageCostBreakdown(
|
||||
usage_type=usage_type,
|
||||
quantity=quantity,
|
||||
cost_cents=cost,
|
||||
)
|
||||
)
|
||||
|
||||
stored_period = BillingPeriodResponse(
|
||||
id=str(billing_period.id),
|
||||
period_start=billing_period.period_start,
|
||||
period_end=billing_period.period_end,
|
||||
seat_cost=billing_period.seat_cost,
|
||||
seat_count=billing_period.seat_count,
|
||||
usage_costs=billing_period.usage_costs,
|
||||
usage_quantities=billing_period.usage_quantities,
|
||||
usage_breakdown=usage_breakdown,
|
||||
total_cost=billing_period.total_cost,
|
||||
status=billing_period.status,
|
||||
)
|
||||
|
||||
return BillingDashboardResponse(
|
||||
current_period=stored_period,
|
||||
past_periods=[],
|
||||
total_spent_all_time=stored_period.total_cost,
|
||||
project_breakdown=[], # Not supported for stored periods
|
||||
)
|
||||
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid period ID format")
|
||||
|
||||
# Handle custom date range if provided
|
||||
if start_date and end_date and isinstance(start_date, str) and isinstance(end_date, str):
|
||||
try:
|
||||
s_date = datetime.fromisoformat(start_date.replace('Z', '+00:00'))
|
||||
e_date = datetime.fromisoformat(end_date.replace('Z', '+00:00'))
|
||||
if e_date.hour == 0 and e_date.minute == 0 and e_date.second == 0:
|
||||
e_date = e_date.replace(hour=23, minute=59, second=59, microsecond=999999)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid date format. Use ISO 8601 format.")
|
||||
|
||||
manual_usage = await billing_service.get_usage_for_period(orm, org_id, s_date, e_date, project_id)
|
||||
manual_usage_costs = await billing_service.calculate_usage_costs(manual_usage)
|
||||
project_usage = await billing_service.get_usage_by_project_for_period(orm, org_id, s_date, e_date)
|
||||
|
||||
usage_breakdown = []
|
||||
for usage_type, quantity in manual_usage.items():
|
||||
cost = manual_usage_costs.get(usage_type, 0)
|
||||
usage_breakdown.append(
|
||||
UsageCostBreakdown(
|
||||
usage_type=usage_type,
|
||||
quantity=quantity,
|
||||
cost_cents=cost,
|
||||
)
|
||||
)
|
||||
|
||||
seat_price = billing_service.get_seat_price()
|
||||
manual_period = BillingPeriodResponse(
|
||||
id="custom",
|
||||
period_start=s_date.isoformat(),
|
||||
period_end=e_date.isoformat(),
|
||||
seat_cost=org.paid_member_count * seat_price,
|
||||
seat_count=org.paid_member_count,
|
||||
usage_costs=manual_usage_costs,
|
||||
usage_quantities=manual_usage,
|
||||
usage_breakdown=usage_breakdown,
|
||||
total_cost=(org.paid_member_count * seat_price) + sum(manual_usage_costs.values()),
|
||||
status="custom",
|
||||
)
|
||||
|
||||
project_breakdown = []
|
||||
if project_usage:
|
||||
usage_costs_service = billing_service
|
||||
for proj_id, usage_data in project_usage.items():
|
||||
# If project_id filter is specified, only include that project
|
||||
if project_id and proj_id != project_id:
|
||||
continue
|
||||
project_usage_dict = {'tokens': usage_data['tokens'], 'spans': usage_data['spans']}
|
||||
project_costs = await usage_costs_service.calculate_usage_costs(project_usage_dict)
|
||||
|
||||
project_breakdown.append(
|
||||
ProjectUsageBreakdown(
|
||||
project_id=proj_id,
|
||||
project_name=usage_data['project_name'],
|
||||
tokens=usage_data['tokens'],
|
||||
spans=usage_data['spans'],
|
||||
token_cost=project_costs.get('tokens', 0),
|
||||
span_cost=project_costs.get('spans', 0),
|
||||
total_cost=project_costs.get('tokens', 0) + project_costs.get('spans', 0),
|
||||
)
|
||||
)
|
||||
|
||||
return BillingDashboardResponse(
|
||||
current_period=manual_period,
|
||||
past_periods=[],
|
||||
total_spent_all_time=manual_period.total_cost,
|
||||
project_breakdown=project_breakdown,
|
||||
)
|
||||
|
||||
# Use Stripe billing period by default, or custom date range if provided
|
||||
|
||||
current_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
|
||||
current_end = now
|
||||
|
||||
logger.info(f"Initial billing period for org {org_id}: {current_start} to {current_end}")
|
||||
|
||||
if org.subscription_id and STRIPE_SECRET_KEY:
|
||||
try:
|
||||
stripe.api_key = STRIPE_SECRET_KEY
|
||||
subscription = stripe.Subscription.retrieve(org.subscription_id)
|
||||
|
||||
if subscription:
|
||||
subscription_status = subscription.get('status', 'unknown')
|
||||
|
||||
if subscription_status in ['trialing', 'active']:
|
||||
from .orgs import extract_subscription_period_dates
|
||||
|
||||
period_start, period_end = extract_subscription_period_dates(subscription)
|
||||
|
||||
if period_start and period_end:
|
||||
current_start = datetime.fromtimestamp(period_start, tz=timezone.utc)
|
||||
current_end = datetime.fromtimestamp(period_end, tz=timezone.utc)
|
||||
logger.info(
|
||||
f"Using Stripe billing period for org {org_id}: "
|
||||
f"{current_start} to {current_end}"
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
f"Could not extract dates from Stripe subscription {org.subscription_id}"
|
||||
)
|
||||
logger.warning(f"Falling back to monthly calendar period for org {org_id}")
|
||||
else:
|
||||
starts_at = subscription.get('start_date') or subscription.get('started_at')
|
||||
if starts_at and subscription_status in ['scheduled', 'incomplete']:
|
||||
scheduled_start = datetime.fromtimestamp(starts_at, tz=timezone.utc)
|
||||
scheduled_end = scheduled_start + timedelta(days=30)
|
||||
|
||||
current_start = scheduled_start
|
||||
current_end = scheduled_end
|
||||
|
||||
else:
|
||||
logger.warning(
|
||||
f"Subscription {org.subscription_id} has unsupported status "
|
||||
f"'{subscription_status}' - falling back to monthly calendar period"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to retrieve Stripe subscription {org.subscription_id}: {e}")
|
||||
logger.warning(
|
||||
f"Falling back to monthly calendar period for org {org_id} due to Stripe error"
|
||||
)
|
||||
|
||||
logger.info(f"Final billing period for org {org_id}: {current_start} to {current_end}")
|
||||
current_usage = await billing_service.get_usage_for_period(
|
||||
orm, org_id, current_start, current_end, project_id
|
||||
)
|
||||
project_usage = await billing_service.get_usage_by_project_for_period(
|
||||
orm, org_id, current_start, current_end
|
||||
)
|
||||
|
||||
current_period = None
|
||||
if current_usage or org.paid_member_count > 0:
|
||||
usage_costs = await billing_service.calculate_usage_costs(current_usage)
|
||||
|
||||
seat_price = billing_service.get_seat_price()
|
||||
|
||||
usage_breakdown = []
|
||||
for usage_type, quantity in current_usage.items():
|
||||
cost = usage_costs.get(usage_type, 0)
|
||||
usage_breakdown.append(
|
||||
UsageCostBreakdown(
|
||||
usage_type=usage_type,
|
||||
quantity=quantity,
|
||||
cost_cents=cost,
|
||||
)
|
||||
)
|
||||
|
||||
current_period = BillingPeriodResponse(
|
||||
id="current",
|
||||
period_start=current_start,
|
||||
period_end=current_end,
|
||||
seat_cost=org.paid_member_count * seat_price,
|
||||
seat_count=org.paid_member_count,
|
||||
usage_costs=usage_costs,
|
||||
usage_quantities=current_usage,
|
||||
usage_breakdown=usage_breakdown,
|
||||
total_cost=(org.paid_member_count * seat_price) + sum(usage_costs.values()),
|
||||
status="current",
|
||||
)
|
||||
|
||||
# For now, we're not showing historical periods since we're moving away from stored periods
|
||||
# In the future, this could be calculated from Stripe's billing history if needed
|
||||
past_period_responses = []
|
||||
total_spent = current_period.total_cost if current_period else 0
|
||||
|
||||
is_legacy = False
|
||||
legacy_cancellation_date = None
|
||||
|
||||
if org.subscription_id and STRIPE_SECRET_KEY:
|
||||
try:
|
||||
subscription = stripe.Subscription.retrieve(org.subscription_id)
|
||||
has_current_pricing = False
|
||||
subscription_items = subscription.get('items', {}).get('data', [])
|
||||
logger.info(f"Subscription has {len(subscription_items)} items")
|
||||
|
||||
for item in subscription_items:
|
||||
price_id = item.get('price', {}).get('id')
|
||||
logger.info(
|
||||
f"Subscription item price ID: {price_id}, "
|
||||
f"current price ID: {STRIPE_SUBSCRIPTION_PRICE_ID}"
|
||||
)
|
||||
if price_id == STRIPE_SUBSCRIPTION_PRICE_ID:
|
||||
has_current_pricing = True
|
||||
break
|
||||
|
||||
# Legacy if no current pricing found OR subscription is canceled/canceling
|
||||
is_canceling = (
|
||||
subscription.get('cancel_at_period_end', False)
|
||||
or subscription.get('canceled_at') is not None
|
||||
or subscription.get('cancel_at') is not None
|
||||
or subscription.get('status') in ['canceled', 'unpaid', 'incomplete_expired']
|
||||
)
|
||||
is_legacy = not has_current_pricing or is_canceling
|
||||
logger.info(
|
||||
f"Legacy determination: has_current_pricing={has_current_pricing}, "
|
||||
f"is_canceling={is_canceling}, status={subscription.get('status')}, "
|
||||
f"is_legacy={is_legacy}"
|
||||
)
|
||||
|
||||
if is_legacy:
|
||||
cancellation_timestamp = None
|
||||
date_source = None
|
||||
|
||||
if subscription.get('cancel_at'):
|
||||
cancellation_timestamp = subscription['cancel_at']
|
||||
date_source = "cancel_at"
|
||||
elif subscription.get('current_period_end'):
|
||||
cancellation_timestamp = subscription['current_period_end']
|
||||
date_source = "current_period_end"
|
||||
elif subscription.get('canceled_at'):
|
||||
cancellation_timestamp = subscription['canceled_at']
|
||||
date_source = "canceled_at"
|
||||
|
||||
if cancellation_timestamp:
|
||||
legacy_cancellation_date = datetime.fromtimestamp(
|
||||
cancellation_timestamp, tz=timezone.utc
|
||||
)
|
||||
logger.info(
|
||||
f"Set legacy cancellation date from Stripe {date_source}: "
|
||||
f"{legacy_cancellation_date}"
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
f"Legacy subscription {org.subscription_id} has no cancellation date fields"
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to check legacy subscription status: {e}")
|
||||
import traceback
|
||||
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
if is_legacy and not legacy_cancellation_date and current_period:
|
||||
legacy_cancellation_date = current_period.period_end
|
||||
logger.info(
|
||||
f"Using current period end as legacy cancellation date fallback: {legacy_cancellation_date}"
|
||||
)
|
||||
|
||||
project_breakdown = []
|
||||
if project_usage:
|
||||
usage_costs_service = billing_service
|
||||
for proj_id, usage_data in project_usage.items():
|
||||
# If project_id filter is specified, only include that project
|
||||
if project_id and proj_id != project_id:
|
||||
continue
|
||||
project_usage_dict = {'tokens': usage_data['tokens'], 'spans': usage_data['spans']}
|
||||
project_costs = await usage_costs_service.calculate_usage_costs(project_usage_dict)
|
||||
|
||||
project_breakdown.append(
|
||||
ProjectUsageBreakdown(
|
||||
project_id=proj_id,
|
||||
project_name=usage_data['project_name'],
|
||||
tokens=usage_data['tokens'],
|
||||
spans=usage_data['spans'],
|
||||
token_cost=project_costs.get('tokens', 0),
|
||||
span_cost=project_costs.get('spans', 0),
|
||||
total_cost=project_costs.get('tokens', 0) + project_costs.get('spans', 0),
|
||||
)
|
||||
)
|
||||
|
||||
return BillingDashboardResponse(
|
||||
current_period=current_period,
|
||||
past_periods=past_period_responses,
|
||||
total_spent_all_time=total_spent,
|
||||
is_legacy_billing=is_legacy,
|
||||
legacy_cancellation_date=legacy_cancellation_date,
|
||||
project_breakdown=project_breakdown,
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,188 @@
|
||||
import uuid
|
||||
from fastapi import Request, Depends, HTTPException
|
||||
|
||||
from agentops.common.orm import get_orm_session, Session
|
||||
from agentops.api.models.metrics import TraceCountsModel
|
||||
|
||||
from ..models import OrgModel, ProjectModel, Environment
|
||||
from ..schemas import (
|
||||
StatusResponse,
|
||||
ProjectSummaryResponse,
|
||||
ProjectResponse,
|
||||
ProjectCreateSchema,
|
||||
ProjectUpdateSchema,
|
||||
)
|
||||
|
||||
|
||||
async def get_projects(
|
||||
*,
|
||||
request: Request,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> list[ProjectSummaryResponse]:
|
||||
"""
|
||||
Get all projects the user has access to across all organizations they belong to.
|
||||
Includes organization information with each project.
|
||||
|
||||
Optimized version that reduces unnecessary data loading.
|
||||
"""
|
||||
# Use a more efficient query that only loads what we need for the response
|
||||
projects = ProjectModel.get_all_for_user_optimized(orm, request.state.session.user_id)
|
||||
|
||||
# Only fetch trace counts if we have projects
|
||||
if projects:
|
||||
_projects_counts = await TraceCountsModel.select(
|
||||
filters={'project_ids': [str(project.id) for project in projects]}
|
||||
)
|
||||
projects_counts: dict[str, int] = {str(p.project_id): p for p in _projects_counts}
|
||||
else:
|
||||
projects_counts = {}
|
||||
|
||||
project_responses = []
|
||||
for project in projects:
|
||||
response = ProjectSummaryResponse.model_validate(project)
|
||||
|
||||
# add trace metrics to the response
|
||||
if counts := projects_counts.get(str(project.id)):
|
||||
response.span_count = counts.span_count
|
||||
response.trace_count = counts.trace_count
|
||||
|
||||
project_responses.append(response)
|
||||
|
||||
return project_responses
|
||||
|
||||
|
||||
def get_project(
|
||||
*,
|
||||
request: Request,
|
||||
project_id: str,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> ProjectResponse:
|
||||
"""
|
||||
Get a specific project by ID.
|
||||
User must be a member of the project's organization.
|
||||
"""
|
||||
project = ProjectModel.get_by_id(orm, project_id)
|
||||
|
||||
if not project or not project.org.is_user_member(request.state.session.user_id):
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
project.org.set_current_user(request.state.session.user_id)
|
||||
return ProjectResponse.model_validate(project)
|
||||
|
||||
|
||||
def create_project(
|
||||
*,
|
||||
request: Request,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
body: ProjectCreateSchema,
|
||||
) -> ProjectResponse:
|
||||
"""
|
||||
Create a new project in an organization.
|
||||
User must be an admin or owner of the organization.
|
||||
"""
|
||||
org = OrgModel.get_by_id(orm, body.org_id)
|
||||
|
||||
if not org or not org.is_user_admin_or_owner(request.state.session.user_id):
|
||||
raise HTTPException(status_code=404, detail="Organization not found")
|
||||
|
||||
if org.max_project_count and not org.current_project_count < org.max_project_count:
|
||||
raise HTTPException(status_code=403, detail="Organization has reached it's project limit")
|
||||
|
||||
environment = Environment(body.environment) if body.environment else Environment.development
|
||||
project = ProjectModel(
|
||||
name=body.name,
|
||||
org_id=body.org_id,
|
||||
environment=environment,
|
||||
)
|
||||
|
||||
orm.add(project)
|
||||
orm.commit()
|
||||
|
||||
# explicitly load the project so we have all context needed for the response
|
||||
project = ProjectModel.get_by_id(orm, project.id)
|
||||
project.org.set_current_user(request.state.session.user_id)
|
||||
return ProjectResponse.model_validate(project)
|
||||
|
||||
|
||||
def update_project(
|
||||
*,
|
||||
request: Request,
|
||||
project_id: str,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
body: ProjectUpdateSchema,
|
||||
) -> ProjectResponse:
|
||||
"""
|
||||
Update a project's name or environment.
|
||||
User must be an admin or owner of the organization.
|
||||
"""
|
||||
project = ProjectModel.get_by_id(orm, project_id)
|
||||
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
if not project.org.is_user_admin_or_owner(request.state.session.user_id):
|
||||
raise HTTPException(status_code=403, detail="You don't have permission to update this project")
|
||||
|
||||
if body.name is not None:
|
||||
project.name = body.name
|
||||
|
||||
if body.environment is not None:
|
||||
try:
|
||||
project.environment = Environment(body.environment)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Invalid environment")
|
||||
|
||||
orm.commit()
|
||||
|
||||
# reload project cuz it's more flexible than calling orm.refresh with args
|
||||
project = ProjectModel.get_by_id(orm, project.id)
|
||||
project.org.set_current_user(request.state.session.user_id)
|
||||
return ProjectResponse.model_validate(project)
|
||||
|
||||
|
||||
def delete_project(
|
||||
*,
|
||||
request: Request,
|
||||
project_id: str,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> StatusResponse:
|
||||
"""
|
||||
Delete a project.
|
||||
User must be an owner of the organization.
|
||||
"""
|
||||
project = ProjectModel.get_by_id(orm, project_id)
|
||||
|
||||
if not project:
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
if not project.org.is_user_owner(request.state.session.user_id):
|
||||
raise HTTPException(status_code=403, detail="Only organization owners can delete projects")
|
||||
|
||||
orm.delete(project)
|
||||
orm.commit()
|
||||
|
||||
return StatusResponse(message="Project deleted successfully")
|
||||
|
||||
|
||||
def regenerate_api_key(
|
||||
*,
|
||||
request: Request,
|
||||
project_id: str,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> ProjectResponse:
|
||||
"""
|
||||
Regenerate the API key for a project.
|
||||
User must be an admin or owner of the organization.
|
||||
"""
|
||||
project = ProjectModel.get_by_id(orm, project_id)
|
||||
|
||||
if not project or not project.org.is_user_admin_or_owner(request.state.session.user_id):
|
||||
raise HTTPException(status_code=404, detail="Project not found")
|
||||
|
||||
project.api_key = str(uuid.uuid4())
|
||||
orm.commit()
|
||||
|
||||
# reload project cuz it's more flexible than calling orm.refresh with args
|
||||
project = ProjectModel.get_by_id(orm, project.id)
|
||||
project.org.set_current_user(request.state.session.user_id)
|
||||
return ProjectResponse.model_validate(project)
|
||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 29 KiB |
@@ -0,0 +1,70 @@
|
||||
from typing import Optional
|
||||
from fastapi import Request, Depends
|
||||
|
||||
from agentops.common.orm import get_orm_session, Session
|
||||
|
||||
from ..models import UserModel
|
||||
from ..schemas import StatusResponse, UserResponse, UserUpdateSchema
|
||||
|
||||
|
||||
def get_user(
|
||||
*,
|
||||
request: Request,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> UserResponse:
|
||||
"""
|
||||
Get all details for the authenticated user.
|
||||
"""
|
||||
# TODO I kinda want to return only a subset of the available fields on most
|
||||
# requests, but really it's just the billing address I don't think we should
|
||||
# be sending around all the time.
|
||||
user: Optional[UserModel] = UserModel.get_by_id(orm, request.state.session.user_id)
|
||||
assert user, "User not found"
|
||||
|
||||
# Create the response, using billing_email (from auth.users) if available
|
||||
# This ensures we return the canonical email from auth.users
|
||||
response = UserResponse.model_validate(user)
|
||||
if user.billing_email:
|
||||
response.email = user.billing_email
|
||||
|
||||
return response
|
||||
|
||||
|
||||
def update_user(
|
||||
*,
|
||||
request: Request,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
body: UserUpdateSchema,
|
||||
) -> UserResponse:
|
||||
"""
|
||||
Update the authenticated user's details.
|
||||
"""
|
||||
user: Optional[UserModel] = UserModel.get_by_id(orm, request.state.session.user_id)
|
||||
assert user, "User not found"
|
||||
|
||||
update_dict = body.model_dump(exclude_unset=True, exclude_none=True)
|
||||
for key, value in update_dict.items():
|
||||
setattr(user, key, value)
|
||||
|
||||
orm.commit()
|
||||
|
||||
# re-fetch user with relationships loaded instead of using refresh with args
|
||||
user = UserModel.get_by_id(orm, request.state.session.user_id)
|
||||
return UserResponse.model_validate(user)
|
||||
|
||||
|
||||
def update_user_survey_complete(
|
||||
*,
|
||||
request: Request,
|
||||
orm: Session = Depends(get_orm_session),
|
||||
) -> StatusResponse:
|
||||
"""
|
||||
Mark the authenticated user's survey as complete.
|
||||
"""
|
||||
user: Optional[UserModel] = UserModel.get_by_id(orm, request.state.session.user_id)
|
||||
assert user, "User not found"
|
||||
|
||||
user.mark_survey_complete()
|
||||
orm.commit()
|
||||
|
||||
return StatusResponse(message="User survey marked complete")
|
||||
@@ -0,0 +1 @@
|
||||
# these are the public views for interacting with hosted agents
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user