5* User queries are routed, analyzed collaboratively, and synthesized into holistic advice.
6* Based on the Multi-Agent AI Support Simulation structure.
7* Uses OpenAI via /v/std/openai.
8*
9* Last Updated: 2025-04-18
171<p class="description">
172Your Personal Life Operating System. Integrate goals, wellness, career, finances, relationships, and creativity.
173<br>How can LifeSync help you synchronize your life today? (Using OpenAI via <code>/v/std/openai</code>)
174<br>Current Date: ${currentDate}
175</p>
322// Includes LifeSync agent flow
323export default async function(req: Request) {
324const { OpenAI } = await import("https://esm.town/v/std/openai");
325326// --- Helper Function: Call OpenAI API ---
327// (Mostly unchanged, but updated the JSON mode check)
328async function callOpenAI(
329systemPrompt: string,
330userMessage: string,
332): Promise<{ role: "assistant" | "system"; content: string }> {
333try {
334// Ensure OPENAI_API_KEY is set in Val Town secrets (environment variable)
335const openai = new OpenAI();
336337const response = await openai.chat.completions.create({
338model: model,
339messages: [
347348if (!response.choices?.[0]?.message?.content) {
349console.error("OpenAI API returned an unexpected or empty response structure:", JSON.stringify(response));
350throw new Error("Received invalid or empty response from AI model.");
351}
357} catch (error) {
358console.error(
359`OpenAI API call failed for model ${model}. System Prompt: ${systemPrompt.substring(0, 80)}... Error:`,
360error,
361);
365let statusCode = error.status || (error.response ? error.response.status : null);
366if (error.response && error.response.data && error.response.data.error) {
367errorMessage = `OpenAI Error (${statusCode || "unknown status"}): ${
368error.response.data.error.message || JSON.stringify(error.response.data.error)
369}`;
372}
373if (statusCode === 401)
374errorMessage = "OpenAI API Error (401): Authentication failed. Verify API key secret ('openai').";
375else if (statusCode === 429) errorMessage = "OpenAI API Error (429): Rate limit or quota exceeded.";
376else if (statusCode === 400) errorMessage = `OpenAI API Error (400): Bad Request. ${error.message || ""}`;
377else if (statusCode >= 500) errorMessage = `OpenAI Server Error (${statusCode}): Issue on OpenAI's side.`;
378else if (error.code === "ENOTFOUND" || error.code === "ECONNREFUSED")
379errorMessage = `Network Error (${error.code}): Cannot connect to OpenAI API.`;
380381// Return error: JSON for Routing agent, plain text for others
442// --- 1. Routing Step ---
443conversationLog.push({ agent: "โ๏ธ System", message: "Contacting Query Routing Agent..." });
444const routingResponse = await callOpenAI(routingAgentSystemPrompt, trimmedQuery);
445446let relevantDomains: string[] = ["GENERAL"]; // Default
449let routingLogMessage = "";
450451if (routingResponse.role === "system") { // Error from callOpenAI
452routingLogMessage = routingResponse.content; // Log the system error
453routingFailed = true;
525526// Pass the summary from the routing agent to the specialist agent
527const specialistResponse = await callOpenAI(agentDetails.prompt, summary);
528529if (specialistResponse.role === "system") {
573574// Use a potentially stronger model for synthesis if needed
575const synthesisResponse = await callOpenAI(
576synthesisInput,
577"Synthesize the above into a cohesive response for the user.",
stevensDemo.cursorrules4 matches
100Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.
101102### OpenAI
103```ts
104import { OpenAI } from "https://esm.town/v/std/openai";
105const openai = new OpenAI();
106const completion = await openai.chat.completions.create({
107messages: [
108{ role: "user", content: "Say hello in a creative way" },
stevensDemo.cursorrules4 matches
100Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.
101102### OpenAI
103```ts
104import { OpenAI } from "https://esm.town/v/std/openai";
105const openai = new OpenAI();
106const completion = await openai.chat.completions.create({
107messages: [
108{ role: "user", content: "Say hello in a creative way" },
promptEvolvermain.tsx8 matches
67// โโโโโโโโ Val.town/Backend Imports โโโโโโโโ //
8import { OpenAI } from "https://esm.town/v/std/openai"; // For backend API call
9import { html } from "https://esm.town/v/stevekrouse/html"; // For serving HTML
10444async function runImprovementPipeline(
445originalText: string,
446openai: OpenAI,
447): Promise<{ improvedText: string; coreIntentSummary: string }> {
448console.log("Pipeline Step 1: Starting Intent Extraction for text length:", originalText.length);
450try {
451const intentPrompt = createIntentExtractionPrompt(originalText);
452const intentCompletion = await openai.chat.completions.create({
453model: AI_MODEL,
454messages: [{ role: "user", content: intentPrompt }],
467let improvedText = originalText;
468try {
469const mainCompletion = await openai.chat.completions.create({
470model: AI_MODEL,
471messages: [{ role: "user", content: mainImprovementPrompt }],
488export default async function server(req: Request): Promise<Response> {
489const url = new URL(req.url);
490const apiKey = Deno.env.get("OPENAI_API_KEY");
491492if (!apiKey) {
493// ... (API key error handling remains the same) ...
494const errorMsg = "Server configuration error: OPENAI_API_KEY secret not set.";
495console.error(errorMsg);
496if (req.method === "POST") return Response.json({ error: errorMsg }, { status: 500 });
497return html(`<html><body><h1>Configuration Error</h1><p>${errorMsg}</p></body></html>`, { status: 500 });
498}
499const openai = new OpenAI({ apiKey: apiKey });
500501// --- API Endpoint (POST) ---
508509// Run the pipeline
510const { improvedText, coreIntentSummary } = await runImprovementPipeline(text, openai);
511512// Return results
stevensDemo.cursorrules4 matches
100Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.
101102### OpenAI
103```ts
104import { OpenAI } from "https://esm.town/v/std/openai";
105const openai = new OpenAI();
106const completion = await openai.chat.completions.create({
107messages: [
108{ role: "user", content: "Say hello in a creative way" },
stevensDemo.cursorrules4 matches
100Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.
101102### OpenAI
103```ts
104import { OpenAI } from "https://esm.town/v/std/openai";
105const openai = new OpenAI();
106const completion = await openai.chat.completions.create({
107messages: [
108{ role: "user", content: "Say hello in a creative way" },
stickfigure-stevensDemo.cursorrules4 matches
100Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.
101102### OpenAI
103```ts
104import { OpenAI } from "https://esm.town/v/std/openai";
105const openai = new OpenAI();
106const completion = await openai.chat.completions.create({
107messages: [
108{ role: "user", content: "Say hello in a creative way" },
Wills-AI-Assistant.cursorrules4 matches
100Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.
101102### OpenAI
103```ts
104import { OpenAI } from "https://esm.town/v/std/openai";
105const openai = new OpenAI();
106const completion = await openai.chat.completions.create({
107messages: [
108{ role: "user", content: "Say hello in a creative way" },
fortuitousSalmonFoxmain.tsx2 matches
6import React from "https://esm.sh/react@18.2.0";
7import { blob } from "https://esm.town/v/std/blob";
8import { OpenAI } from "https://esm.town/v/std/openai";
9import { sqlite } from "https://esm.town/v/stevekrouse/sqlite";
10305export default async function server(request: Request): Promise<Response> {
306const KEY = "fortuitousSalmonFox";
307const openai = new OpenAI();
308const url = new URL(request.url);
309
Girlswithjuicemain.tsx2 matches
6import React from "https://esm.sh/react@18.2.0";
7import { blob } from "https://esm.town/v/std/blob";
8import { OpenAI } from "https://esm.town/v/std/openai";
9import { sqlite } from "https://esm.town/v/stevekrouse/sqlite";
10305export default async function server(request: Request): Promise<Response> {
306const KEY = "Girlswithjuice";
307const openai = new OpenAI();
308const url = new URL(request.url);
309