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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
refactor: streaming in cloudflare worker (#518)
Matthew Diakonove015a8ac6a6f
diff --git a/screenpipe-actions/ai-proxy/src/index.ts b/screenpipe-actions/ai-proxy/src/index.tsindex c0be8f291..a80d88135 100644--- a/screenpipe-actions/ai-proxy/src/index.ts+++ b/screenpipe-actions/ai-proxy/src/index.ts@@ -40,68 +40,6 @@ import { Langfuse } from "langfuse-node";// }// }-async function callAI(body: any, env: Env, langfuse: Langfuse): Promise<Response> {- const trace = langfuse.trace({- id: "ai_call_" + Date.now(),- name: "ai_call",- metadata: { expectJson: body.response_format?.type === "json_object" }- });-- const generation = trace.generation({- name: "openai_completion",- startTime: new Date(),- model: body.model,- modelParameters: {- temperature: body.temperature,- expectJson: body.response_format?.type === "json_object"- },- input: body.messages,- output: null- });-- try {- const response = 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)- });-- const data = await response.json();-- if (data.error) {- generation.end({- completionStartTime: new Date(),- completion: data.error.message,- endTime: new Date(),- status: "error"- });- return new Response(JSON.stringify(data), { status: 400 });- }-- generation.end({- completionStartTime: new Date(),- output: data.choices[0]?.message?.content,- endTime: new Date(),- status: "success"- });-- return new Response(JSON.stringify(data), {- headers: { "Content-Type": "application/json" }- });- } catch (error) {- generation.end({- completionStartTime: new Date(),- completion: error.message,- endTime: new Date(),- status: "error"- });- throw error;- }-}-export default {/*** This is the standard fetch handler for a Cloudflare Worker@@ -111,7 +49,7 @@ export default {* @param ctx - The execution context of the Worker* @returns The response to be sent back to the client*/- async fetch(request: Request, env: Env): Promise<Response> {+ async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {const langfuse = new Langfuse({publicKey: env.LANGFUSE_PUBLIC_KEY,secretKey: env.LANGFUSE_SECRET_KEY,@@ -123,23 +61,178 @@ export default {console.error("langfuse error:", error);});+ // CORS headers+ const corsHeaders = {+ "Access-Control-Allow-Origin": "*", // Or specify your app's origin+ "Access-Control-Allow-Methods": "GET, POST, OPTIONS",+ "Access-Control-Allow-Headers": "Content-Type, Authorization, User-Agent",+ };++ // Handle CORS preflight requests+ if (request.method === "OPTIONS") {+ return new Response(null, {+ headers: {+ ...corsHeaders,+ // Add this line to handle preflight requests for all headers+ "Access-Control-Allow-Headers": request.headers.get("Access-Control-Request-Headers") || "",+ }+ });+ }+try {const url = new URL(request.url);const path = url.pathname;if (path === '/test') {- return new Response('ai proxy is working!', { status: 200 });+ return new Response('ai proxy is working!', {+ status: 200,+ headers: corsHeaders+ });}if (path === '/v1/chat/completions' && request.method === 'POST') {const body = await request.json();- return await callAI(body, env, langfuse);+ const isStreaming = body.stream === true;++ const trace = langfuse.trace({+ id: "ai_call_" + Date.now(),+ name: "ai_call",+ metadata: { expectJson: body.response_format?.type === "json_object", streaming: isStreaming }+ });++ const generation = trace.generation({+ name: "openai_completion",+ startTime: new Date(),+ model: body.model,+ modelParameters: {+ temperature: body.temperature,+ expectJson: body.response_format?.type === "json_object",+ streaming: isStreaming+ },+ input: body.messages,+ output: null+ });++ if (isStreaming) {+ const { readable, writable } = new TransformStream();+ const writer = writable.getWriter();++ ctx.waitUntil((async () => {+ try {+ const openaiResponse = 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 (!openaiResponse.ok) {+ const errorData = await openaiResponse.json();+ throw new Error(`OpenAI API error: ${JSON.stringify(errorData)}`);+ }++ const reader = openaiResponse.body?.getReader();+ if (!reader) {+ throw new Error("Failed to get reader from OpenAI 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",+ endTime: new Date(),+ status: "success"+ });+ } catch (error) {+ console.error("Error in OpenAI stream:", error);+ generation.end({+ completionStartTime: new Date(),+ completion: error.message,+ endTime: new Date(),+ status: "error"+ });+ 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 openaiResponse = 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 (!openaiResponse.ok) {+ const errorData = await openaiResponse.json();+ throw new Error(`OpenAI API error: ${JSON.stringify(errorData)}`);+ }++ const data = await openaiResponse.json();++ generation.end({+ completionStartTime: new Date(),+ output: data.choices[0]?.message?.content,+ endTime: new Date(),+ status: "success"+ });++ return new Response(JSON.stringify(data), {+ headers: {+ ...corsHeaders,+ "Content-Type": "application/json"+ }+ });+ } catch (error) {+ console.error("Error in OpenAI request:", error);+ generation.end({+ completionStartTime: new Date(),+ completion: error.message,+ endTime: new Date(),+ status: "error"+ });+ return new Response(JSON.stringify({ error: error.message }), {+ status: 500,+ headers: {+ ...corsHeaders,+ "Content-Type": "application/json"+ }+ });+ }+ }}- return new Response("not found", { status: 404 });+ return new Response("not found", {+ status: 404,+ headers: corsHeaders+ });} catch (error) {console.error("error in fetch:", error);- return new Response("an error occurred", { status: 500 });+ return new Response("an error occurred", {+ status: 500,+ headers: corsHeaders+ });} finally {await langfuse.shutdownAsync();}@@ -152,3 +245,24 @@ interface Env {LANGFUSE_SECRET_KEY: string;ANTHROPIC_API_KEY: string;}++// test+// curl -X POST https://ai-proxy.i-f9f.workers.dev/v1/chat/completions \+// -H "Content-Type: application/json" \+// -H "Authorization: Bearer YOUR_API_KEY" \+// -d '{+// "model": "gpt-4o",+// "messages": [+// {+// "role": "system",+// "content": "You are a helpful assistant."+// },+// {+// "role": "user",+// "content": "Tell me a short joke."+// }+// ],+// "stream": true+// }' | while read -r line; do+// echo "$line" | sed 's/^data: //g' | jq -r '.choices[0].delta.content // empty' 2>/dev/null+// done | tr -d '\n'diff --git a/screenpipe-actions/ai-proxy/wrangler.toml b/screenpipe-actions/ai-proxy/wrangler.tomlindex f933bd64c..0cff895ac 100644--- a/screenpipe-actions/ai-proxy/wrangler.toml+++ b/screenpipe-actions/ai-proxy/wrangler.toml@@ -6,8 +6,8 @@ compatibility_date = "2024-10-11"# Workers Logs# Docs: https://developers.cloudflare.com/workers/observability/logs/workers-logs/# Configuration: https://developers.cloudflare.com/workers/observability/logs/workers-logs/#enable-workers-logs-# [observability]-# enabled = true+[observability]+enabled = true# Automatically place your workloads in an optimal location to minimize latency.# If you are running back-end logic in a Worker, running it closer to your back-end infrastructure