Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

feat: functionality of screenpipe cloud (#1215)

Mintu Gogoi7ee0464c3916
diff --git a/screenpipe-actions/ai-proxy/bun.lockb b/screenpipe-actions/ai-proxy/bun.lockb
index 7307f9fad..a3d232ca7 100755
Binary files a/screenpipe-actions/ai-proxy/bun.lockb and b/screenpipe-actions/ai-proxy/bun.lockb differ
diff --git a/screenpipe-actions/ai-proxy/package.json b/screenpipe-actions/ai-proxy/package.json
index e00de8d37..7cc1d9d06 100644
--- a/screenpipe-actions/ai-proxy/package.json
+++ b/screenpipe-actions/ai-proxy/package.json
@@ -17,7 +17,9 @@
"dependencies": {
"@anthropic-ai/sdk": "^0.33.1",
"@clerk/backend": "^1.21.3",
- "@sentry/cloudflare": "^8.51.0",
- "langfuse-node": "^3.27.0"
+ "@google/generative-ai": "^0.21.0",
+ "langfuse-node": "^3.27.0",
+ "openai": "^4.80.1",
+ "@sentry/cloudflare": "^8.51.0"
}
}
diff --git a/screenpipe-actions/ai-proxy/src/index.ts b/screenpipe-actions/ai-proxy/src/index.ts
index b3fa48f62..03132d157 100644
--- a/screenpipe-actions/ai-proxy/src/index.ts
+++ b/screenpipe-actions/ai-proxy/src/index.ts
@@ -1,7 +1,8 @@
import { DurableObject } from 'cloudflare:workers';
import { Langfuse } from 'langfuse-node';
import { verifyToken } from '@clerk/backend';
-import { Anthropic } from '@anthropic-ai/sdk';
+import { createProvider } from './providers';
+import { Env, RequestBody } from './types';
import * as Sentry from '@sentry/cloudflare';
// Add cache for subscription status
@@ -134,6 +135,23 @@ export class RateLimiter {
}
}
+async function handleChatCompletions(body: RequestBody, env: Env): Promise<Response> {
+ const provider = createProvider(body.model, env);
+
+ if (body.stream) {
+ const stream = await provider.createStreamingCompletion(body);
+ return new Response(stream, {
+ headers: {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ Connection: 'keep-alive',
+ },
+ });
+ }
+
+ return await provider.createCompletion(body);
+}
+
export default Sentry.withSentry(
(env) => ({
dsn: 'https://60750a679399e9d0b8631c059fb7578d@o4507617161314304.ingest.us.sentry.io/4508689350983680',
@@ -242,254 +260,44 @@ export default Sentry.withSentry(
});
}
- if (path === '/v1/chat/completions' && request.method === 'POST') {
- const body = (await request.json()) as {
- model: string;
- messages: any[];
- stream: boolean;
- response_format?: { type: string };
- temperature?: number;
- };
- const isStreaming = body.stream === true;
- const isAnthropicModel = body.model.toLowerCase().includes('claude');
- const isGeminiModel = body.model.toLowerCase().includes('gemini');
-
- const trace = langfuse.trace({
- id: 'ai_call_' + Date.now(),
- name: 'ai_call',
- metadata: {
- expectJson: body.response_format?.type === 'json_object',
- streaming: isStreaming,
- provider: isAnthropicModel ? 'anthropic' : isGeminiModel ? 'gemini' : 'openai',
- },
- });
+ if (path === '/v1/chat/completions' && request.method === 'POST') {
+ const body = (await request.json()) as RequestBody;
+ const isStreaming = body.stream === true;
+
+ const trace = langfuse.trace({
+ id: 'ai_call_' + Date.now(),
+ name: 'ai_call',
+ metadata: {
+ model: body.model,
+ streaming: body.stream === true,
+ },
+ });
- const generation = trace.generation({
- name: 'completion',
- model: body.model,
- modelParameters: {
- temperature: body.temperature,
- streaming: isStreaming,
+ try {
+ const response = await handleChatCompletions(body, env);
+ await trace.update({
+ metadata: {
+ completionStatus: 'success',
+ completionTime: new Date().toISOString(),
+ modelUsed: body.model,
+ isStreaming: body.stream === true,
+ },
+ output: response.statusText,
+ });
+ return response;
+ } catch (error: any) {
+ await trace.update({
+ metadata: {
+ completionStatus: 'error',
+ errorTime: new Date().toISOString(),
+ errorType: error.name,
+ errorMessage: error.message,
},
- input: JSON.stringify(body.messages),
+ output: error.message,
});
-
- // Convert messages to Anthropic format if needed
- const anthropicMessages = isAnthropicModel
- ? {
- messages: body.messages.map((msg) => ({
- role: msg.role === 'user' ? 'user' : 'assistant',
- content: msg.content,
- })),
- model: body.model,
- stream: isStreaming,
- temperature: body.temperature,
- max_tokens: 8192,
- }
- : null;
-
- if (isStreaming) {
- const { readable, writable } = new TransformStream();
- const writer = writable.getWriter();
-
- ctx.waitUntil(
- (async () => {
- try {
- if (isAnthropicModel) {
- const anthropic = new Anthropic({
- apiKey: env.ANTHROPIC_API_KEY,
- });
-
- try {
- const stream = await anthropic.messages.create({
- messages: body.messages.map((msg) => ({
- role: msg.role === 'user' ? 'user' : 'assistant',
- content: msg.content,
- })),
- model: body.model,
- stream: true,
- max_tokens: 4096,
- });
-
- for await (const chunk of stream) {
- if (chunk.type === 'content_block_delta' && chunk.delta?.type === 'text_delta') {
- const openaiChunk = {
- choices: [
- {
- delta: {
- content: chunk.delta.text,
- },
- },
- ],
- };
- await writer.write(new TextEncoder().encode(`data: ${JSON.stringify(openaiChunk)}\n\n`));
- }
- }
-
- await writer.write(new TextEncoder().encode('data: [DONE]\n\n'));
- } catch (error) {
- console.error('Error in Anthropic stream:', error);
- throw error;
- }
- } else if (isGeminiModel) {
- const apiResponse = await fetch('https://generativelanguage.googleapis.com/v1beta/openai/chat/completions', {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${env.GEMINI_API_KEY}`,
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(body),
- });
-
- if (!apiResponse.ok) {
- const errorData = await apiResponse.json();
- throw new Error(`API error: ${JSON.stringify(errorData)}`);
- }
-
- const reader = apiResponse.body?.getReader();
- if (!reader) {
- throw new Error('Failed to get reader from API response');
- }
-
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- await writer.write(value);
- }
- } else {
- // Original OpenAI format - keep the fetch call only for OpenAI
- const apiResponse = await fetch('https://api.openai.com/v1/chat/completions', {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${env.OPENAI_API_KEY}`,
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(body),
- });
-
- if (!apiResponse.ok) {
- const errorData = await apiResponse.json();
- throw new Error(`API error: ${JSON.stringify(errorData)}`);
- }
-
- const reader = apiResponse.body?.getReader();
- if (!reader) {
- throw new Error('Failed to get reader from API response');
- }
-
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- await writer.write(value);
- }
- }
-
- generation.end({
- completionStartTime: new Date(),
- output: 'Streaming response completed',
- });
- } catch (error: any) {
- console.error('Error in API stream:', error);
- generation.end({
- completionStartTime: new Date(),
- output: error.message,
- });
- await writer.write(new TextEncoder().encode(`data: ${JSON.stringify({ error: error.message })}\n\n`));
- } finally {
- await writer.close();
- }
- })()
- );
-
- return new Response(readable, {
- headers: {
- ...corsHeaders,
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- Connection: 'keep-alive',
- },
- });
- } else {
- // Non-streaming response
- try {
- const apiResponse = await fetch(
- isAnthropicModel
- ? 'https://api.anthropic.com/v1/messages'
- : isGeminiModel
- ? 'https://generativelanguage.googleapis.com/v1beta/openai/chat/completions'
- : 'https://api.openai.com/v1/chat/completions',
- {
- method: 'POST',
- headers: {
- ...(isAnthropicModel
- ? {
- 'x-api-key': env.ANTHROPIC_API_KEY,
- 'anthropic-version': '2023-06-01',
- }
- : isGeminiModel
- ? {
- Authorization: `Bearer ${env.GEMINI_API_KEY}`,
- }
- : {
- Authorization: `Bearer ${env.OPENAI_API_KEY}`,
- }),
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(isAnthropicModel ? anthropicMessages : body),
- }
- );
-
- if (!apiResponse.ok) {
- const errorData = await apiResponse.json();
- throw new Error(`API error: ${JSON.stringify(errorData)}`);
- }
-
- const data: any = await apiResponse.json();
-
- // Handle both OpenAI-style and Anthropic-style responses
- const content = isAnthropicModel
- ? // Anthropic format: either content array or direct message
- data.content?.[0]?.text || data.choices?.[0]?.message?.content || ''
- : // OpenAI format
- data.choices?.[0]?.message?.content || '';
-
- const normalizedResponse = {
- choices: [
- {
- message: {
- content: content,
- },
- },
- ],
- };
-
- generation.end({
- completionStartTime: new Date(),
- output: normalizedResponse.choices[0]?.message?.content || '',
- });
-
- return new Response(JSON.stringify(normalizedResponse), {
- headers: {
- ...corsHeaders,
- 'Content-Type': 'application/json',
- },
- });
- } catch (error: any) {
- console.error('Error in API request:', error);
- generation.end({
- completionStartTime: new Date(),
- output: error.message,
- });
- return new Response(JSON.stringify({ error: error.message }), {
- status: 500,
- headers: {
- ...corsHeaders,
- 'Content-Type': 'application/json',
- },
- });
- }
- }
- }
+ throw error;
+ }
+ }
if (path === '/v1/listen' && request.method === 'POST') {
// Get the raw body instead of form data
@@ -558,19 +366,6 @@ export default Sentry.withSentry(
} satisfies ExportedHandler<Env>
);
-interface Env {
- OPENAI_API_KEY: string;
- LANGFUSE_PUBLIC_KEY: string;
- LANGFUSE_SECRET_KEY: string;
- ANTHROPIC_API_KEY: string;
- DEEPGRAM_API_KEY: string;
- RATE_LIMITER: DurableObjectNamespace;
- GEMINI_API_KEY: string;
- NODE_ENV?: string;
- SUPABASE_URL: string;
- SUPABASE_ANON_KEY: string;
- CLERK_SECRET_KEY: string;
-}
/*
terminal 1
diff --git a/screenpipe-actions/ai-proxy/src/providers/anthropic.ts b/screenpipe-actions/ai-proxy/src/providers/anthropic.ts
new file mode 100644
index 000000000..816408c14
--- /dev/null
+++ b/screenpipe-actions/ai-proxy/src/providers/anthropic.ts
@@ -0,0 +1,153 @@
+import { AIProvider } from './base';
+import { Message, RequestBody, Tool, AnthropicTool } from '../types';
+import Anthropic from '@anthropic-ai/sdk';
+import type {
+ MessageParam,
+ ContentBlock,
+ TextBlock,
+ ImageBlockParam,
+ Message as AnthropicMessage,
+ ContentBlockParam,
+} from '@anthropic-ai/sdk/resources';
+
+export class AnthropicProvider implements AIProvider {
+ supportsTools = true;
+ supportsVision = true;
+ supportsJson = true;
+ private client: Anthropic;
+
+ constructor(apiKey: string) {
+ this.client = new Anthropic({ apiKey });
+ }
+
+ async createCompletion(body: RequestBody): Promise<Response> {
+ const messages = this.formatMessages(body.messages);
+
+ const response = await this.client.messages.create({
+ messages,
+ model: body.model,
+ max_tokens: 4096,
+ temperature: body.temperature,
+ system: body.response_format?.type === 'json_object' ? 'Respond with valid JSON only.' : undefined,
+ tools: body.tools ? this.formatTools(body.tools) : undefined,
+ });
+
+ return new Response(JSON.stringify(this.formatResponse(response)), {
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ async createStreamingCompletion(body: RequestBody): Promise<ReadableStream> {
+ const stream = await this.client.messages.create({
+ messages: this.formatMessages(body.messages),
+ model: body.model,
+ stream: true,
+ max_tokens: 4096,
+ temperature: body.temperature,
+ });
+
+ return new ReadableStream({
+ async start(controller) {
+ try {
+ for await (const chunk of stream) {
+ if (chunk.type === 'content_block_delta' && chunk.delta?.type === 'text_delta') {
+ controller.enqueue(
+ new TextEncoder().encode(
+ `data: ${JSON.stringify({
+ choices: [{ delta: { content: chunk.delta.text } }],
+ })}\n\n`
+ )
+ );
+ }
+ }
+ controller.enqueue(new TextEncoder().encode('data: [DONE]\n\n'));
+ controller.close();
+ } catch (error) {
+ controller.error(error);
+ }
+ },
+ });
+ }
+
+ private formatTools(tools: Tool[]): AnthropicTool[] {
+ return tools.map((tool) => ({
+ name: tool.function.name,
+ description: tool.function.description,
+ input_schema: {
+ type: 'object',
+ properties: tool.function.parameters.properties,
+ required: tool.function.parameters.required,
+ ...Object.entries(tool.function.parameters)
+ .filter(([key]) => !['type', 'properties', 'required'].includes(key))
+ .reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {}),
+ },
+ }));
+ }
+
+ formatMessages(messages: Message[]): MessageParam[] {
+ return messages.map((msg) => {
+ const content: ContentBlockParam[] = Array.isArray(msg.content)
+ ? msg.content.map((part) => {
+ if (part.type === 'image') {
+ return {
+ type: 'image',
+ source: {
+ type: 'base64',
+ media_type: 'image/jpeg',
+ data: part.image?.url || '',
+ },
+ } as ImageBlockParam;
+ }
+ return {
+ type: 'text',
+ text: part.text || '',
+ } as TextBlock;
+ })
+ : [
+ {
+ type: 'text',
+ text: msg.content as string,
+ },
+ ];
+
+ return {
+ role: msg.role === 'user' ? 'user' : 'assistant',
+ content,
+ };
+ });
+ }
+
+ formatResponse(response: AnthropicMessage): {
+ choices: Array<{
+ message: {
+ content: string;
+ role: string;
+ tool_calls?: any[];
+ };
+ }>;
+ } {
+ const textBlock = response.content.find((block): block is TextBlock => block.type === 'text');
+
+ const textContent = textBlock?.text || '';
+
+ return {
+ choices: [
+ {
+ message: {
+ content: textContent,
+ role: 'assistant',
+ tool_calls: response.content
+ .filter((block): block is ContentBlock => block.type === 'tool_use')
+ .map((block) => ({
+ type: block.type,
+ function: {
+ name: (block as any).name,
+ arguments: JSON.stringify((block as any).input),
+ },
+ })),
+ },
+ },
+ ],
+ };
+ }
+}
diff --git a/screenpipe-actions/ai-proxy/src/providers/base.ts b/screenpipe-actions/ai-proxy/src/providers/base.ts
new file mode 100644
index 000000000..a505512be
--- /dev/null
+++ b/screenpipe-actions/ai-proxy/src/providers/base.ts
@@ -0,0 +1,12 @@
+import { Message, RequestBody } from '../types';
+
+export interface AIProvider {
+ supportsTools: boolean;
+ supportsVision: boolean;
+ supportsJson: boolean;
+
+ createCompletion(body: RequestBody): Promise<Response>;
+ createStreamingCompletion(body: RequestBody): Promise<ReadableStream>;
+ formatMessages(messages: Message[]): any;
+ formatResponse(response: any): any;
+}
diff --git a/screenpipe-actions/ai-proxy/src/providers/gemini.ts b/screenpipe-actions/ai-proxy/src/providers/gemini.ts
new file mode 100644
index 000000000..f0bdf50db
--- /dev/null
+++ b/screenpipe-actions/ai-proxy/src/providers/gemini.ts
@@ -0,0 +1,123 @@
+import { AIProvider } from './base';
+import { Message, RequestBody } from '../types';
+import { GoogleGenerativeAI, GenerativeModel } from '@google/generative-ai';
+
+export class GeminiProvider implements AIProvider {
+ supportsTools = true;
+ supportsVision = true;
+ supportsJson = true;
+ private client: GoogleGenerativeAI;
+ private model!: GenerativeModel;
+
+ constructor(apiKey: string) {
+ this.client = new GoogleGenerativeAI(apiKey);
+ }
+
+ async createCompletion(body: RequestBody): Promise<Response> {
+ this.model = this.client.getGenerativeModel({ model: body.model });
+
+ const chat = this.model.startChat({
+ history: this.formatMessages(body.messages),
+ generationConfig: {
+ temperature: body.temperature,
+ },
+ });
+
+ const prompt =
+ body.response_format?.type === 'json_object'
+ ? `${body.messages[body.messages.length - 1].content}\nRespond with valid JSON only.`
+ : (body.messages[body.messages.length - 1].content as string);
+
+ const result = await chat.sendMessage(prompt);
+ const response = await result.response;
+
+ return new Response(JSON.stringify(this.formatResponse(response)), {
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ async createStreamingCompletion(body: RequestBody): Promise<ReadableStream> {
+ this.model = this.client.getGenerativeModel({ model: body.model });
+
+ const chat = this.model.startChat({
+ history: this.formatMessages(body.messages),
+ generationConfig: {
+ temperature: body.temperature,
+ },
+ });
+
+ const result = await chat.sendMessage(body.messages[body.messages.length - 1].content as string);
+
+ return new ReadableStream({
+ async start(controller) {
+ try {
+ const response = await result.response;
+ const text = response.text();
+
+ const chunkSize = 20;
+ for (let i = 0; i < text.length; i += chunkSize) {
+ const chunk = text.slice(i, i + chunkSize);
+ controller.enqueue(
+ new TextEncoder().encode(
+ `data: ${JSON.stringify({
+ choices: [{ delta: { content: chunk } }],
+ })}\n\n`
+ )
+ );
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+
+ controller.enqueue(new TextEncoder().encode('data: [DONE]\n\n'));
+ controller.close();
+ } catch (error) {
+ controller.error(error);
+ }
+ },
+ });
+ }
+
+ formatMessages(messages: Message[]): any[] {
+ return messages.map((msg) => ({
+ role: this.mapRole(msg.role),
+ parts: Array.isArray(msg.content)
+ ? msg.content.map((part) => {
+ if (part.type === 'image') {
+ return {
+ inlineData: {
+ mimeType: 'image/jpeg',
+ data: part.image?.url,
+ },
+ };
+ }
+ return { text: part.text || '' };
+ })
+ : [{ text: msg.content as string }],
+ }));
+ }
+
+ private mapRole(role: string): string {
+ switch (role) {
+ case 'user':
+ return 'user';
+ case 'assistant':
+ return 'model';
+ case 'system':
+ return 'user';
+ default:
+ return 'user';
+ }
+ }
+
+ formatResponse(response: any): any {
+ return {
+ choices: [
+ {
+ message: {
+ content: response.text(),
+ role: 'assistant',
+ },
+ },
+ ],
+ };
+ }
+}
diff --git a/screenpipe-actions/ai-proxy/src/providers/index.ts b/screenpipe-actions/ai-proxy/src/providers/index.ts
new file mode 100644
index 000000000..27e038909
--- /dev/null
+++ b/screenpipe-actions/ai-proxy/src/providers/index.ts
@@ -0,0 +1,17 @@
+import { OpenAIProvider } from './openai';
+import { AnthropicProvider } from './anthropic';
+import { GeminiProvider } from './gemini';
+import { AIProvider } from './base';
+import { Env } from '../types';
+
+export function createProvider(model: string, env: Env): AIProvider {
+ if (model.toLowerCase().includes('claude')) {
+ return new AnthropicProvider(env.ANTHROPIC_API_KEY);
+ }
+ if (model.toLowerCase().includes('gemini')) {
+ return new GeminiProvider(env.GEMINI_API_KEY);
+ }
+ return new OpenAIProvider(env.OPENAI_API_KEY);
+}
+
+export type { AIProvider };
diff --git a/screenpipe-actions/ai-proxy/src/providers/openai.ts b/screenpipe-actions/ai-proxy/src/providers/openai.ts
new file mode 100644
index 000000000..15daed0ea
--- /dev/null
+++ b/screenpipe-actions/ai-proxy/src/providers/openai.ts
@@ -0,0 +1,108 @@
+import { AIProvider } from './base';
+import { Message, RequestBody } from '../types';
+import OpenAI from 'openai';
+import type { ChatCompletionMessage, ChatCompletionCreateParams } from 'openai/resources/chat';
+
+export class OpenAIProvider implements AIProvider {
+ supportsTools = true;
+ supportsVision = true;
+ supportsJson = true;
+ private client: OpenAI;
+
+ constructor(apiKey: string) {
+ this.client = new OpenAI({ apiKey });
+ }
+
+ async createCompletion(body: RequestBody): Promise<Response> {
+ const messages = this.formatMessages(body.messages);
+
+ const params: ChatCompletionCreateParams = {
+ model: body.model,
+ messages,
+ temperature: body.temperature,
+ stream: false,
+ response_format: body.response_format?.type === 'json_object' ? { type: 'json_object' } : undefined,
+ tools: body.tools as ChatCompletionCreateParams['tools'],
+ tool_choice: body.tool_choice as ChatCompletionCreateParams['tool_choice'],
+ };
+
+ const response = await this.client.chat.completions.create(params);
+ return new Response(JSON.stringify(this.formatResponse(response)), {
+ headers: { 'Content-Type': 'application/json' },
+ });
+ }
+
+ async createStreamingCompletion(body: RequestBody): Promise<ReadableStream> {
+ const stream = await this.client.chat.completions.create({
+ model: body.model,
+ messages: this.formatMessages(body.messages),
+ temperature: body.temperature,
+ stream: true,
+ response_format: body.response_format?.type === 'json_object' ? { type: 'json_object' } : undefined,
+ tools: body.tools as ChatCompletionCreateParams['tools'],
+ });
+
+ return new ReadableStream({
+ async start(controller) {
+ try {
+ for await (const chunk of stream) {
+ const content = chunk.choices[0]?.delta?.content;
+ if (content) {
+ controller.enqueue(
+ new TextEncoder().encode(
+ `data: ${JSON.stringify({
+ choices: [{ delta: { content } }],
+ })}\n\n`
+ )
+ );
+ }
+ }
+ controller.enqueue(new TextEncoder().encode('data: [DONE]\n\n'));
+ controller.close();
+ } catch (error) {
+ controller.error(error);
+ }
+ },
+ });
+ }
+
+ formatMessages(messages: Message[]): ChatCompletionMessage[] {
+ return messages.map(
+ (msg) =>
+ ({
+ role: msg.role,
+ content: Array.isArray(msg.content)
+ ? msg.content.map((part) => {
+ if (part.type === 'image') {
+ return {
+ type: 'image_url',
+ image_url: {
+ url: part.image?.url,
+ detail: 'auto',
+ },
+ };
+ }
+ return { type: 'text', text: part.text || '' };
+ })
+ : msg.content,
+ tool_calls: msg.tool_calls,
+ name: msg.name,
+ refusal: null,
+ } as ChatCompletionMessage)
+ );
+ }
+
+ formatResponse(response: any): any {
+ return {
+ choices: [
+ {
+ message: {
+ content: response.choices[0].message.content,
+ role: 'assistant',
+ tool_calls: response.choices[0].message.tool_calls,
+ },
+ },
+ ],
+ };
+ }
+}
diff --git a/screenpipe-actions/ai-proxy/src/types.ts b/screenpipe-actions/ai-proxy/src/types.ts
new file mode 100644
index 000000000..202039dee
--- /dev/null
+++ b/screenpipe-actions/ai-proxy/src/types.ts
@@ -0,0 +1,127 @@
+import type Anthropic from '@anthropic-ai/sdk';
+
+export interface Message {
+ role: 'system' | 'user' | 'assistant' | 'tool';
+ content: string | ContentPart[];
+ name?: string;
+ tool_calls?: ToolCall[];
+}
+
+export interface ContentPart {
+ type: 'text' | 'image' | 'file';
+ text?: string;
+ image?: { url: string };
+ data?: Uint8Array | string;
+ mimeType?: string;
+}
+
+export interface ToolCall {
+ id: string;
+ type: 'function';
+ function: {
+ name: string;
+ arguments: string;
+ };
+}
+
+export type OpenAITool = {
+ type: 'function';
+ function: {
+ name: string;
+ description: string;
+ parameters: {
+ type: 'object';
+ properties: Record<string, any>;
+ required?: string[];
+ };
+ };
+};
+
+export type AnthropicTool = Anthropic.Tool;
+
+export type GeminiTool = {
+ functionDeclarations: Array<{
+ name: string;
+ description: string;
+ parameters: {
+ type: 'object';
+ properties: Record<string, any>;
+ required?: string[];
+ };
+ }>;
+};
+
+export interface Tool {
+ type: 'function';
+ function: {
+ name: string;
+ description: string;
+ parameters: {
+ type: 'object';
+ properties: Record<string, any>;
+ required?: string[];
+ };
+ };
+}
+
+export interface RequestBody {
+ model: string;
+ messages: Message[];
+ stream?: boolean;
+ tools?: any[];
+ temperature?: number;
+ tool_choice?: string | { type: 'function'; function: { name: string } };
+ response_format?: ResponseFormat;
+}
+
+export interface ResponseFormat {
+ type: 'text' | 'json_object';
+ schema?: Record<string, any>;
+}
+
+export interface ImageContent {
+ type: 'image';
+ image_url: {
+ url: string;
+ detail?: 'low' | 'high' | 'auto';
+ };
+}
+
+export interface OpenAIResponse {
+ choices: Array<{
+ message: {
+ content: string;
+ role: string;
+ };
+ }>;
+}
+
+export interface AnthropicResponse {
+ content: Array<{
+ text: string;
+ }>;
+}
+
+export interface GeminiResponse {
+ candidates: Array<{
+ content: {
+ parts: Array<{
+ text: string;
+ }>;
+ };
+ }>;
+}
+
+export interface Env {
+ OPENAI_API_KEY: string;
+ LANGFUSE_PUBLIC_KEY: string;
+ LANGFUSE_SECRET_KEY: string;
+ ANTHROPIC_API_KEY: string;
+ DEEPGRAM_API_KEY: string;
+ RATE_LIMITER: DurableObjectNamespace;
+ CLERK_SECRET_KEY: string;
+ GEMINI_API_KEY: string;
+ SUPABASE_URL: string;
+ SUPABASE_ANON_KEY: string;
+ NODE_ENV: string;
+}