Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ Edit the .env file with your Tinybird API key and other configuration.
NEXT_PUBLIC_TINYBIRD_API_URL=http://localhost:7181
# read_pipes token
NEXT_PUBLIC_TINYBIRD_API_KEY=
# optional: llm_events_append token (append-only on llm_events) to log the app's own AI calls.
# If unset, those calls are not logged. Never use the admin token here.
TINYBIRD_EVENTS_TOKEN=
```

Start the Next.js application:
Expand Down Expand Up @@ -136,7 +139,7 @@ NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/
```

The [middleware](https://github.com/tinybirdco/ai-analytics-template/blob/main/dashboard/ai-analytics/src/middleware.ts) will get the `org:name` permission from the Clerk user and use it to create a Tinybird JWT token with the `organization` dimension fixed to that value. Read more about Tinybird JWT tokens [here](https://www.tinybird.co/docs/forward/get-started/authentication#json-web-tokens-jwts).
The [middleware](https://github.com/tinybirdco/ai-analytics-template/blob/main/dashboard/ai-analytics/src/middleware.ts) will get the `org:name` permission from the Clerk user and use it to create a Tinybird JWT token with the `organization` dimension fixed to that value. When `TINYBIRD_JWT_SECRET` is set, logged-out users and users without an organization get no Tinybird token and see an empty dashboard until they sign in with an organization. Read more about Tinybird JWT tokens [here](https://www.tinybird.co/docs/forward/get-started/authentication#json-web-tokens-jwts).

## Mock Data

Expand Down
4 changes: 4 additions & 0 deletions TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ tb --cloud token copy read_pipes && TINYBIRD_TOKEN=$(pbpaste)
open https://llm-tracker.tinybird.live\?token\=$TINYBIRD_TOKEN
```

## Log the app's own AI calls

The dashboard's AI features log their LLM calls to `llm_events` when `TINYBIRD_EVENTS_TOKEN` is set. Use the `llm_events_append` token (append-only on `llm_events`), never the admin token. If it's unset, those calls aren't logged.

## Local development, multi-tenancy, customization and more

See [README.md](https://github.com/tinybirdco/llm-performance-tracker?tab=readme-ov-file#build-and-deploy-your-own-llm-tracker)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,30 @@ import { createOpenAI } from '@ai-sdk/openai';
import { generateObject } from 'ai';
import { z } from 'zod';
import { NextResponse } from 'next/server';
import { fetchAvailableDimensions } from '@/lib/dimensions';
import { fetchAvailableDimensions, isAllowedTinybirdApiUrl } from '@/lib/dimensions';
import { extractDatesFromQuery } from '@/lib/dateUtils';
import { generateRandomChatId, hashApiKeyUser, wrapModelWithTinybird } from '@/lib/tinybird-wrapper';

const MAX_QUERY_LENGTH = 1000;

// Update the POST function to properly map meta with data
export async function POST(req: Request) {
try {
const { query, apiKey } = await req.json();
const token = req.headers.get('x-custom-tinybird-token');
const apiUrl = req.headers.get('x-custom-tinybird-api-url');


if (apiUrl && !isAllowedTinybirdApiUrl(apiUrl)) {
return NextResponse.json({ error: 'Invalid Tinybird API URL' }, { status: 400 });
}

if (!query) {
return NextResponse.json({ error: 'Query is required' }, { status: 400 });
}

if (typeof query !== 'string' || query.length > MAX_QUERY_LENGTH) {
return NextResponse.json({ error: `Query must be a string of at most ${MAX_QUERY_LENGTH} characters` }, { status: 400 });
}

if (!apiKey) {
return NextResponse.json({ error: 'OpenAI API key is required' }, { status: 400 });
Expand Down Expand Up @@ -87,7 +97,7 @@ export async function POST(req: Request) {
const wrappedOpenAI = wrapModelWithTinybird(
openai('gpt-3.5-turbo'),
process.env.NEXT_PUBLIC_TINYBIRD_API_URL!,
process.env.TINYBIRD_JWT_SECRET!,
process.env.TINYBIRD_EVENTS_TOKEN,
{
event: 'ai_cost_calculator',
environment: process.env.NODE_ENV,
Expand Down Expand Up @@ -145,8 +155,9 @@ export async function POST(req: Request) {

// Fetch the llm_usage pipe definition
const fetchPipeDefinition = async (token: string | null, apiUrl: string | null) => {
const TINYBIRD_API_URL = apiUrl || 'http://localhost:7181';
const TINYBIRD_API_KEY = token || process.env.NEXT_PUBLIC_TINYBIRD_API_KEY;
// The server token only goes to the server URL. A caller-supplied URL needs the caller's own token.
const TINYBIRD_API_URL = apiUrl || process.env.NEXT_PUBLIC_TINYBIRD_API_URL || 'http://localhost:7181';
const TINYBIRD_API_KEY = apiUrl ? token : (token || process.env.NEXT_PUBLIC_TINYBIRD_API_KEY);

if (!TINYBIRD_API_KEY) {
console.error('No Tinybird API key available');
Expand Down
11 changes: 10 additions & 1 deletion dashboard/ai-analytics/src/app/api/generate-embedding/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import type { FeatureExtractionPipeline } from '@xenova/transformers/types/pipel
// Cache the model to avoid reloading it for every request
let embeddingPipeline: FeatureExtractionPipeline | null = null;

const MAX_TEXT_LENGTH = 1000;

async function getEmbeddingModel() {
if (!embeddingPipeline) {
embeddingPipeline = await pipeline('feature-extraction', 'Xenova/all-MiniLM-L6-v2') as FeatureExtractionPipeline;
Expand All @@ -23,7 +25,14 @@ export async function POST(req: Request) {
{ status: 400 }
);
}


if (text.length > MAX_TEXT_LENGTH) {
return NextResponse.json(
{ error: `Invalid input: text must be at most ${MAX_TEXT_LENGTH} characters` },
{ status: 400 }
);
}

// Get the model
const model = await getEmbeddingModel();

Expand Down
15 changes: 12 additions & 3 deletions dashboard/ai-analytics/src/app/api/search/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,23 @@ import { createOpenAI } from '@ai-sdk/openai';
import { generateObject } from 'ai';
import { z } from 'zod';
import { generateRandomChatId, hashApiKeyUser, wrapModelWithTinybird } from '@/lib/tinybird-wrapper';
import { fetchAvailableDimensions } from '@/lib/dimensions';
import { fetchAvailableDimensions, isAllowedTinybirdApiUrl } from '@/lib/dimensions';

const MAX_PROMPT_LENGTH = 1000;

export async function POST(req: Request) {
const { prompt, apiKey } = await req.json();
const token = req.headers.get('x-custom-tinybird-token');
const apiUrl = req.headers.get('x-custom-tinybird-api-url');


if (apiUrl && !isAllowedTinybirdApiUrl(apiUrl)) {
return Response.json({ error: 'Invalid Tinybird API URL' }, { status: 400 });
}

if (typeof prompt !== 'string' || prompt.length > MAX_PROMPT_LENGTH) {
return Response.json({ error: `Prompt must be a string of at most ${MAX_PROMPT_LENGTH} characters` }, { status: 400 });
}

if (!apiKey) {
return Response.json({ error: 'OpenAI API key is required' }, { status: 400 });
}
Expand Down Expand Up @@ -39,7 +48,7 @@ export async function POST(req: Request) {
const wrappedOpenAI = wrapModelWithTinybird(
openai('gpt-3.5-turbo'),
process.env.NEXT_PUBLIC_TINYBIRD_API_URL!,
process.env.TINYBIRD_JWT_SECRET!,
process.env.TINYBIRD_EVENTS_TOKEN,
{
event: 'search_filter',
environment: process.env.NODE_ENV,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ response = await acompletion(
snippet: `const wrappedOpenAI = wrapModelWithTinybird(
openai('gpt-3.5-turbo'),
process.env.NEXT_PUBLIC_TINYBIRD_API_URL!,
process.env.TINYBIRD_JWT_SECRET!,
process.env.TINYBIRD_EVENTS_TOKEN,
{
event: 'search_filter',
environment: process.env.NODE_ENV,
Expand Down
14 changes: 13 additions & 1 deletion dashboard/ai-analytics/src/lib/dimensions.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
// Only Tinybird API hosts (plus localhost outside production) to avoid SSRF via caller-supplied URLs
export const isAllowedTinybirdApiUrl = (apiUrl: string | null) => {
if (!apiUrl) return false;
if (/^https:\/\/api\.([a-z0-9-]+\.)*tinybird\.co\/?$/.test(apiUrl)) return true;
return process.env.NODE_ENV !== 'production' && /^http:\/\/localhost(:\d+)?\/?$/.test(apiUrl);
};

export const fetchAvailableDimensions = async (token: string | null, apiUrl: string | null) => {
if (!token) {
console.error('No Tinybird token available');
return null;
}


if (!isAllowedTinybirdApiUrl(apiUrl)) {
console.error('Invalid Tinybird API URL');
return null;
}

try {
const url = `${apiUrl}/v0/pipes/llm_dimensions.json`;
const response = await fetch(url, {
Expand Down
5 changes: 4 additions & 1 deletion dashboard/ai-analytics/src/lib/tinybird-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,12 @@ type TinybirdConfig = {
export function wrapModelWithTinybird(
model: LanguageModelV1,
tinybirdApiUrl: string,
tinybirdToken: string,
tinybirdToken: string | undefined,
config: TinybirdConfig = {}
) {
// No append token configured: skip logging instead of falling back to another token
if (!tinybirdToken) return model;

const originalDoGenerate = model.doGenerate;
const originalDoStream = model.doStream;

Expand Down
65 changes: 50 additions & 15 deletions dashboard/ai-analytics/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,45 @@ import { NextResponse } from "next/server"
import * as jose from 'jose'
import { getApiUrlFromHost, extractHostFromToken } from './lib/tinybird-utils'

console.log('MIDDLEWARE FILE LOADED!!!')
// Multi-tenant mode: users only get data through a per-org JWT, never the shared read token
const isMultiTenant = !!process.env.TINYBIRD_JWT_SECRET

// Basic per-IP rate limit for the AI routes. In-memory, so it only applies per server
// instance (per isolate on Edge). Use a shared store if you need a global limit.
const RATE_LIMITED_ROUTES = ['/api/search', '/api/extract-cost-parameters', '/api/generate-embedding']
const RATE_LIMIT_PER_MINUTE = 30
const rateLimitHits = new Map<string, { count: number; reset: number }>()

function isRateLimited(ip: string) {
const now = Date.now()
const entry = rateLimitHits.get(ip)
if (!entry || now > entry.reset) {
if (rateLimitHits.size > 10000) rateLimitHits.clear()
rateLimitHits.set(ip, { count: 1, reset: now + 60_000 })
return false
}
entry.count++
return entry.count > RATE_LIMIT_PER_MINUTE
}

function responseWithoutJwt() {
const response = NextResponse.next()
if (!isMultiTenant) {
response.headers.set('x-tinybird-token', process.env.NEXT_PUBLIC_TINYBIRD_API_KEY || '')
}
return response
}

export default clerkMiddleware(async (auth, request) => {
debugger;
console.log('🔥🔥🔥 MIDDLEWARE EXECUTING 🔥🔥🔥')
if (RATE_LIMITED_ROUTES.includes(request.nextUrl.pathname)) {
const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim() || 'unknown'
if (isRateLimited(ip)) {
return NextResponse.json({ error: 'Too many requests' }, { status: 429 })
}
}

const authentication = await auth()
const { userId, sessionId, sessionClaims, orgId, orgRole, orgPermissions } = authentication
console.log('Auth details:', { userId, sessionId, sessionClaims, orgId, orgRole, orgPermissions })
const { userId, sessionId, orgPermissions } = authentication

// Get the token from the URL if present
const url = new URL(request.url);
Expand All @@ -32,18 +63,26 @@ export default clerkMiddleware(async (auth, request) => {
return response;
}

// If user is not authenticated, continue without modification
// If user is not authenticated, continue without a JWT
if (!userId || !sessionId) {
console.log('No user or session found')

const response = NextResponse.next()
response.headers.set('x-tinybird-token', process.env.NEXT_PUBLIC_TINYBIRD_API_KEY || '')
return response
return responseWithoutJwt()
}

// Single-tenant mode has no secret to sign a JWT with: everyone uses the read token
if (!isMultiTenant) {
return responseWithoutJwt()
}

try {
const orgName = orgPermissions?.[0]?.split(':').pop() || ''

// An empty organization makes the pipes skip the filter and return every org,
// so users without an org are treated like logged-out visitors
if (!orgName) {
return responseWithoutJwt()
}

// Create Tinybird JWT
const secret = new TextEncoder().encode(process.env.TINYBIRD_JWT_SECRET)
const token = await new jose.SignJWT({
Expand Down Expand Up @@ -79,8 +118,6 @@ export default clerkMiddleware(async (auth, request) => {
})
.setProtectedHeader({ alg: 'HS256' })
.sign(secret)
debugger;
console.log('Generated token:', token)

// Clone the response and add token
const response = NextResponse.next()
Expand All @@ -89,9 +126,7 @@ export default clerkMiddleware(async (auth, request) => {
return response
} catch (error) {
console.error('Middleware error:', error)
const response = NextResponse.next()
response.headers.set('x-tinybird-token', process.env.NEXT_PUBLIC_TINYBIRD_API_KEY || '')
return response
return responseWithoutJwt()
}
})

Expand Down
6 changes: 2 additions & 4 deletions tinybird/datasources/llm_events.datasource
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
TOKEN "llm_events_append" APPEND

DESCRIPTION >
Store LLM events with usage metrics, costs, and metadata
Expand Down Expand Up @@ -43,7 +44,4 @@ SCHEMA >
ENGINE "MergeTree"
ENGINE_PARTITION_KEY "toYYYYMM(timestamp)"
ENGINE_SORTING_KEY "timestamp, organization, project, environment, user, chat_id"
ENGINE_PRIMARY_KEY "timestamp, organization, project"

FORWARD_QUERY >
SELECT timestamp, organization, project, environment, user, chat_id, message_id, model, prompt_tokens, completion_tokens, total_tokens, response_time, duration, cost, exception, traceback, response_status, messages, response_choices, proxy_metadata, provider, llm_api_duration_ms, end_time, id, CAST(stream, 'Bool') AS stream, call_type, api_key, log_event_type, CAST(cache_hit, 'Bool') AS cache_hit, response, response_id, response_object, defaultValueOfTypeName('Array(Float32)') AS embedding
ENGINE_PRIMARY_KEY "timestamp, organization, project"
Loading