Search
Code3,248
import { Hono } from "npm:hono@4.4.12";// @ts-ignoreimport { OpenAI } from "https://esm.town/v/std/openai?v=4";// --- TownCar: The JIT Journey Engine v1.1 (AI Concierge Service) ---const app = new Hono();async function callOpenAI(c, messages, response_format = { type: "text" }) { const openai = new OpenAI(); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: messages, if (!completion || !completion.choices || completion.choices.length === 0) { console.error("Invalid response from OpenAI API:", JSON.stringify(completion, null, 2)); throw new Error("The AI service returned an invalid or empty response."); } try { const messages = [{ role: "system", content: META_PROMPTS.ROUTE_PLANNER.replace("{{goal}}", goal) }]; const planJson = await callOpenAI(c, messages, { type: "json_object" }); return c.json(JSON.parse(planJson)); } catch (e) { content: META_PROMPTS.ROUTE_PLANNER_RETRY.replace("{{goal}}", goal), }]; const retryPlanJson = await callOpenAI(c, retryMessages, { type: "json_object" }); return c.json(JSON.parse(retryPlanJson)); } catch (retryError) { content: META_PROMPTS.STOP_ARCHITECT.replace("{{task}}", task).replace("{{context}}", contextString), }]; const specJson = await callOpenAI(c, architectMessages, { type: "json_object" }); const spec = JSON.parse(specJson); if (spec.inputs && spec.inputs.length > 0) { const uiBuilderMessages = [{ role: "system", content: META_PROMPTS.UI_BUILDER.replace("{{spec}}", specJson) }]; uiJson = await callOpenAI(c, uiBuilderMessages, { type: "json_object" }); } const contextString = JSON.stringify(context, null, 2); const specJson = await callOpenAI(c, [{ role: "system", content: META_PROMPTS.STOP_ARCHITECT.replace("{{task}}", task).replace("{{context}}", contextString), }], { type: "json_object" }); let executionPrompt = await callOpenAI(c, [{ role: "system", content: META_PROMPTS.LOGIC_WEAVER.replace("{{spec}}", specJson).replace("{{context}}", contextString), } const openai = new OpenAI(); const aiStream = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "user", content: executionPrompt }],
import { Hono } from "npm:hono@4.4.12";// @ts-ignoreimport { OpenAI } from "https://esm.town/v/std/openai?v=4";// @ts-ignoreimport { blob } from "https://esm.town/v/std/blob";// --- HELPER FUNCTIONS ---async function callOpenAI(messages, response_format = { type: "text" }) { const openai = new OpenAI(); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: messages, try { const planMessages = [{ role: "system", content: META_PROMPTS.WORKFLOW_PLANNER.replace("{{goal}}", input) }]; const planJson = await callOpenAI(planMessages, { type: "json_object" }); let plan = JSON.parse(planJson); for (const step of plan.steps) { const contextString = JSON.stringify(stepContext, null, 2); const specJson = await callOpenAI( [{ role: "system", { type: "json_object" }, ); const executionPrompt = await callOpenAI([{ role: "system", content: META_PROMPTS.LOGIC_WEAVER.replace("{{spec}}", specJson).replace("{{context}}", contextString), }]); const stepOutput = await callOpenAI([{ role: "user", content: executionPrompt }]); const outputKey = `step_${step.id}_output`; stepContext[outputKey] = stepOutput; try { const messages = [{ role: "system", content: META_PROMPTS.WORKFLOW_PLANNER.replace("{{goal}}", input) }]; const planJson = await callOpenAI(messages, { type: "json_object" }); let plan = JSON.parse(planJson); if (Array.isArray(plan)) { try { const contextString = JSON.stringify(taskData.metadata.context, null, 2); const specJson = await callOpenAI( [{ role: "system", { type: "json_object" }, ); let executionPrompt = await callOpenAI([{ role: "system", content: META_PROMPTS.LOGIC_WEAVER.replace("{{spec}}", specJson).replace("{{context}}", contextString), }]); const stepOutput = await callOpenAI([{ role: "user", content: executionPrompt }]); // Create a new compliant artifact for the step output
import { Hono } from "npm:hono@4.4.12";// @ts-ignoreimport { OpenAI } from "https://esm.town/v/std/openai?v=4";// --- Emergent: The JIT Workflow Engine v3.0 (Autonomous Task Architect) ---const app = new Hono();async function callOpenAI(c, messages, response_format = { type: "text" }) { const openai = new OpenAI(); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: messages, if (!completion || !completion.choices || completion.choices.length === 0) { console.error("Invalid response from OpenAI API:", JSON.stringify(completion, null, 2)); throw new Error("The AI service returned an invalid or empty response."); } try { const messages = [{ role: "system", content: META_PROMPTS.WORKFLOW_PLANNER.replace("{{goal}}", goal) }]; const planJson = await callOpenAI(c, messages, { type: "json_object" }); return c.json(JSON.parse(planJson)); } catch (e) { content: META_PROMPTS.WORKFLOW_PLANNER_RETRY.replace("{{goal}}", goal), }]; const retryPlanJson = await callOpenAI(c, retryMessages, { type: "json_object" }); return c.json(JSON.parse(retryPlanJson)); } catch (retryError) { content: META_PROMPTS.TASK_ARCHITECT.replace("{{task}}", task).replace("{{context}}", contextString), }]; const specJson = await callOpenAI(c, architectMessages, { type: "json_object" }); const spec = JSON.parse(specJson); if (spec.inputs && spec.inputs.length > 0) { const uiBuilderMessages = [{ role: "system", content: META_PROMPTS.UI_BUILDER.replace("{{spec}}", specJson) }]; uiJson = await callOpenAI(c, uiBuilderMessages, { type: "json_object" }); } const contextString = JSON.stringify(context, null, 2); const specJson = await callOpenAI(c, [{ role: "system", content: META_PROMPTS.TASK_ARCHITECT.replace("{{task}}", task).replace("{{context}}", contextString), }], { type: "json_object" }); let executionPrompt = await callOpenAI(c, [{ role: "system", content: META_PROMPTS.LOGIC_WEAVER.replace("{{spec}}", specJson).replace("{{context}}", contextString), } const openai = new OpenAI(); const aiStream = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "user", content: executionPrompt }],
- **Blob storage**: `import { blob } from "https://esm.town/v/std/blob"`- **SQLite**: `import { sqlite } from "https://esm.town/v/stevekrouse/sqlite"`- **OpenAI**: `import { OpenAI } from "https://esm.town/v/std/openai"`- **Email**: `import { email } from "https://esm.town/v/std/email"`
- **Blob storage**: `import { blob } from "https://esm.town/v/std/blob"`- **SQLite**: `import { sqlite } from "https://esm.town/v/stevekrouse/sqlite"`- **OpenAI**: `import { OpenAI } from "https://esm.town/v/std/openai"`- **Email**: `import { email } from "https://esm.town/v/std/email"`
import { Hono } from "npm:hono@4.4.12";// @ts-ignoreimport { OpenAI } from "https://esm.town/v/std/openai?v=4";// --- Banks 7/22/2025. For Leo & Niko. Bugfix for API calls. Final version. <3// --- josh@dereticular.com const userInput = `Occupation: ${occupation.title}, Task: ${task.task}`; try { const openai = new OpenAI(); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "system", content: PROMPT_REFINER_SYSTEM_PROMPT }, { role: "user", content: userInput }], if (!refined_prompt) return c.json({ error: "refined_prompt is required" }, 400); try { const openai = new OpenAI(); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "system", content: INPUT_EXTRACTOR_SYSTEM_PROMPT }, { role: "user", content: refined_prompt }], try { const openai = new OpenAI(); const taskCompletion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "user", content: finalUserPrompt }], if (!taskOutput) throw new Error("The AI returned no content."); const htmlCompletion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "system", content: HTML_FORMATTER_SYSTEM_PROMPT }, { role: "user", content: taskOutput }],
import { Hono } from "npm:hono@4.4.12";// @ts-ignoreimport { OpenAI } from "https://esm.town/v/std/openai?v=4";// --- Banks 7/22/2025. Dental Practice AI Task Automator.// --- josh@dereticular.com const userInput = `Occupation: ${occupation.title}, Task: ${task.task}`; try { const openai = new OpenAI(); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "system", content: PROMPT_REFINER_SYSTEM_PROMPT }, { role: "user", content: userInput }], const userInput = `Occupation: ${occupation_title}, Task: ${task}`; try { const openai = new OpenAI(); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "system", content: PROMPT_REFINER_SYSTEM_PROMPT }, { role: "user", content: userInput }], if (!refined_prompt) return c.json({ error: "refined_prompt is required" }, 400); try { const openai = new OpenAI(); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "system", content: INPUT_EXTRACTOR_SYSTEM_PROMPT }, { role: "user", content: refined_prompt }], const userInput = JSON.stringify({ type: "occupations", industry: industry }); try { const openai = new OpenAI(); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [ const userInput = JSON.stringify({ type: "tasks", occupation: occupation_name }); try { const openai = new OpenAI(); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [ try { const openai = new OpenAI(); const agentCompletion = await openai.chat.completions.create({ model: "gpt-4o", messages: [ throw new Error("The agent returned no content."); } const htmlCompletion = await openai.chat.completions.create({ model: "gpt-4o", messages: [
Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.### OpenAI```tsimport { OpenAI } from "https://esm.town/v/std/openai";const openai = new OpenAI();const completion = await openai.chat.completions.create({ messages: [ { role: "user", content: "Say hello in a creative way" },
id: string; name: string; type: 'yahoo_api' | 'openai' | 'processing'; status: 'pending' | 'loading' | 'success' | 'error'; startTime?: string; stepType = 'yahoo_api'; break; case 'openai_request': stepId = 'openai_request'; stepName = 'OpenAI Analysis Request'; stepType = 'openai'; break; case 'openai_response': stepId = 'openai_response'; stepName = 'OpenAI Analysis Response'; stepType = 'openai'; break; case 'performance':
timestamp: string; sessionId: string; type: 'yahoo_api' | 'mlb_data' | 'openai_request' | 'openai_response' | 'error' | 'performance'; userId?: string; leagueId?: string; summary?: { yahooApiCalls: number; openaiRequests: number; totalTokensUsed: number; errors: number; /** * Log OpenAI request with full prompt */ logOpenAiRequest(model: string, prompt: string, requestConfig: any, retryAttempt: number = 0): void { this.addLogEntry({ type: 'openai_request', data: { model, /** * Log OpenAI response with full content */ logOpenAiResponse(model: string, response: string, executionTime: number, tokenCount?: number): void { this.addLogEntry({ type: 'openai_response', data: { model, const yahooEntries = session.entries.filter(e => e.type === 'yahoo_api'); const openaiRequests = session.entries.filter(e => e.type === 'openai_request'); const openaiResponses = session.entries.filter(e => e.type === 'openai_response'); const errors = session.entries.filter(e => e.type === 'error');## AI Processing- OpenAI Requests: ${openaiRequests.length}- OpenAI Responses: ${openaiResponses.length}- Total Tokens Used: ${openaiResponses.reduce((sum, e) => sum + (e.metadata?.tokenCount || 0), 0)}- Average AI Response Time: ${openaiResponses.length > 0 ? Math.round(openaiResponses.reduce((sum, e) => sum + (e.metadata?.executionTime || 0), 0) / openaiResponses.length) : 0}ms## Errors /** * Extract all OpenAI prompts and responses for analysis */ extractOpenAiData(sessionId: string): any { const session = this.sessions.get(sessionId); if (!session) return null; const openaiRequests = session.entries.filter(e => e.type === 'openai_request'); const openaiResponses = session.entries.filter(e => e.type === 'openai_response'); return { sessionId, timestamp: session.startTime, requests: openaiRequests.map((entry, index) => ({ requestId: index, timestamp: entry.timestamp, config: entry.data.config })), responses: openaiResponses.map((entry, index) => ({ responseId: index, timestamp: entry.timestamp, const yahooData = this.extractYahooData(sessionId); const openaiData = this.extractOpenAiData(sessionId); return `- Total Data Collected: ${yahooData?.yahooApiCalls?.reduce((sum, call) => sum + (call.dataSize || 0), 0)} bytes## OpenAI Processing Quality- Requests Made: ${openaiData?.requests?.length || 0}- Responses Received: ${openaiData?.responses?.length || 0}- Average Prompt Length: ${openaiData?.requests?.reduce((sum, req) => sum + (req.promptLength || 0), 0) / (openaiData?.requests?.length || 1)} characters- Parse Success Rate: ${openaiData?.responses?.filter(r => r.parsedSuccessfully).length / (openaiData?.responses?.length || 1) * 100}%- Average Response Time: ${openaiData?.responses?.reduce((sum, res) => sum + (res.executionTime || 0), 0) / (openaiData?.responses?.length || 1)}ms## Recommendations for Prompt Optimization${this.generatePromptOptimizationRecommendations(openaiData)}`; } }, yahooData: this.extractYahooData(sessionId), openaiData: this.extractOpenAiData(sessionId), performance: session.entries.filter(e => e.type === 'performance'), errors: session.entries.filter(e => e.type === 'error'), private generateSessionSummary(session: LogSession): LogSession['summary'] { const yahooApiCalls = session.entries.filter(e => e.type === 'yahoo_api').length; const openaiRequests = session.entries.filter(e => e.type === 'openai_request').length; const totalTokensUsed = session.entries .filter(e => e.type === 'openai_response') .reduce((sum, e) => sum + (e.metadata?.tokenCount || 0), 0); const errors = session.entries.filter(e => e.type === 'error').length; return { yahooApiCalls, openaiRequests, totalTokensUsed, errors, private calculateDataQualityScore(session: LogSession): number { // Simple scoring based on successful responses and data completeness const totalRequests = session.entries.filter(e => e.type === 'yahoo_api' || e.type === 'openai_request').length; const errors = session.entries.filter(e => e.type === 'error').length; const successfulResponses = session.entries.filter(e => e.type === 'openai_response' && e.data.parsedSuccessfully).length; if (totalRequests === 0) return 0; const errorRate = errors / totalRequests; const successRate = successfulResponses / session.entries.filter(e => e.type === 'openai_request').length; return Math.round((1 - errorRate) * successRate * 100); private analyzeDataQuality(session: LogSession): string { const yahooEntries = session.entries.filter(e => e.type === 'yahoo_api'); const openaiResponses = session.entries.filter(e => e.type === 'openai_response'); const insights = []; } if (openaiResponses.length > 0) { const successfulParses = openaiResponses.filter(e => e.data.parsedSuccessfully).length; const parseSuccessRate = (successfulParses / openaiResponses.length) * 100; insights.push(`- OpenAI JSON parse success rate: ${Math.round(parseSuccessRate)}%`); } const yahooEntries = session.entries.filter(e => e.type === 'yahoo_api'); const openaiRequests = session.entries.filter(e => e.type === 'openai_request'); const openaiResponses = session.entries.filter(e => e.type === 'openai_response'); const errors = session.entries.filter(e => e.type === 'error'); // Check for large prompts const avgPromptSize = openaiRequests.reduce((sum, e) => sum + (e.data.promptLength || 0), 0) / openaiRequests.length; if (avgPromptSize > 5000) { recommendations.push('- Consider reducing prompt size for faster OpenAI responses'); } // Check for parsing errors const parseFailures = openaiResponses.filter(e => !e.data.parsedSuccessfully).length; if (parseFailures > 0) { recommendations.push('- Improve prompt clarity to reduce JSON parsing failures'); // Check for slow responses const slowResponses = openaiResponses.filter(e => (e.metadata?.executionTime || 0) > 15000).length; if (slowResponses > 0) { recommendations.push('- Consider using a faster OpenAI model or reducing prompt complexity'); } } private generatePromptOptimizationRecommendations(openaiData: any): string { if (!openaiData?.requests?.length) { return '- No OpenAI requests to analyze'; } const recommendations = []; const avgPromptLength = openaiData.requests.reduce((sum: number, req: any) => sum + (req.promptLength || 0), 0) / openaiData.requests.length; const avgResponseTime = openaiData.responses?.reduce((sum: number, res: any) => sum + (res.executionTime || 0), 0) / (openaiData.responses?.length || 1); const parseSuccessRate = (openaiData.responses?.filter((r: any) => r.parsedSuccessfully).length || 0) / (openaiData.responses?.length || 1); if (avgPromptLength > 8000) {
reconsumeralization
import { OpenAI } from "https://esm.town/v/std/openai";
import { sqlite } from "https://esm.town/v/stevekrouse/sqlite";
/**
* Practical Implementation of Collective Content Intelligence
* Bridging advanced AI with collaborative content creation
*/
exp
kwhinnery_openai
lost1991
import { OpenAI } from "https://esm.town/v/std/openai";
export default async function(req: Request): Promise<Response> {
if (req.method === "OPTIONS") {
return new Response(null, {
headers: {
"Access-Control-Allow-Origin": "*",
No docs found