Search
Code3,247
* Serves HTML UI & API endpoint from the same Val. * Based on user-provided glassmorphism UI example. * Assumes 'openai' secret is set in Val Town environment variables. * * Last Updated: 2025-05-01 (Reference Relevance & Paradigmatic Analysis Integration)export default async function(req: Request) { // --- Dynamic Imports (Inside Handler) --- const { OpenAI } = await import("https://esm.town/v/std/openai"); const { z } = await import("npm:zod"); const { fetch } = await import("https://esm.town/v/std/fetch"); } // --- Helper Function: Call OpenAI API (Unchanged) --- async function callOpenAI( openai: OpenAI, systemPrompt: string, userMessage: string, ): Promise<{ role: "assistant" | "system"; content: string | object }> { try { const response = await openai.chat.completions.create({ model, messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }], else { return { role: "assistant", content }; } } catch (error) { console.error(`OpenAI call failed (ExpectJSON: ${expectJson}):`, error); let msg = "Error communicating with AI."; if (error.message) msg += ` Details: ${error.message}`; if (error.status === 401) msg = "OpenAI Auth Error."; if (error.status === 429) msg = "OpenAI Rate Limit Exceeded."; return { role: "system", content: msg }; } log: LogEntry[], ): Promise<LogEntry[]> { const openai = new OpenAI(); log.push({ agent: "System", type: "step", message: "Workflow started." }); log.push({ // --- Content Analysis (Unchanged) --- log.push({ agent: "System", type: "step", message: "Analyzing content..." }); const anaRes = await callOpenAI(openai, contentAnalysisSystemPrompt, truncText, "gpt-4o", true); if (anaRes.role === "assistant" && anaRes.content && (anaRes.content as AnalysisResult).summary) { // Type assertion for check log.push({ agent: "Content Analysis Agent", type: "result", message: anaRes.content }); // --- NEW: Paradigmatic Analysis --- log.push({ agent: "System", type: "step", message: "Analyzing document context/paradigm..." }); const paradigmRes = await callOpenAI(openai, paradigmaticAnalysisSystemPrompt, truncText, "gpt-4o", true); if ( paradigmRes.role === "assistant" && paradigmRes.content && (paradigmRes.content as ParadigmaticInfo).documentType // --- MODIFIED: Reference Extraction --- log.push({ agent: "System", type: "step", message: "Extracting references..." }); const refRes = await callOpenAI(openai, referenceExtractionSystemPrompt, truncText, "gpt-4o", true); // Use updated prompt let extRef: Reference[] = []; // Use Reference type // Check the correct key 'references' from the prompt
* Multi-Agent Policy Document Analysis (Single Val Version with PDF Upload & Dashboard Style) * Demonstrates document ingestion (URL, Text, PDF Upload), content analysis, * citation extraction, and basic reference traversal using collaborative AI agents via OpenAI. * Uses 'npm:pdf.js-extract' for direct PDF text extraction within the Val (experimental). * Serves an HTML UI with a dashboard grid background and handles API requests within the same Val. * OpenAI import is dynamically done inside the main server function. * * Based on structure from multi-agent support simulation example. * Assumes 'openai' secret is set in Val Town environment variables. * * Last Updated: 2025-05-01 (Added PDF upload, dashboard style) <p class="description"> Enter a document URL, paste text, or upload a PDF below. AI agents will analyze content, extract citations, and attempt reference traversal.<br> Uses OpenAI via Val Town & <code>npm:pdf.js-extract</code> for PDFs. Current Date: ${ new Date().toLocaleDateString() }export default async function(req: Request) { // --- Dynamic Imports (Inside Handler) --- const { OpenAI } = await import("https://esm.town/v/std/openai"); const { z } = await import("npm:zod"); const { fetch } = await import("https://esm.town/v/std/fetch"); } // --- Helper Function: Call OpenAI API (Unchanged) --- async function callOpenAI( openai: OpenAI, systemPrompt: string, userMessage: string, ): Promise<{ role: "assistant" | "system"; content: string | object }> { try { const response = await openai.chat.completions.create({ model: model, messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }], return { role: "assistant", content: JSON.parse(content) }; } catch (parseError) { console.error("OpenAI JSON Parse Error:", parseError, "Raw Content:", content); throw new Error(`AI response was not valid JSON. Raw: ${content.substring(0, 150)}...`); } } else { return { role: "assistant", content: content }; } } catch (error) { console.error(`OpenAI API call failed. ExpectJSON: ${expectJson}. Error:`, error); let errorMessage = "Error communicating with AI model."; if (error.message) { errorMessage += ` Details: ${error.message}`; } log: LogEntry[], ): Promise<LogEntry[]> { const openai = new OpenAI(); log.push({ agent: "System", type: "step", message: "Starting analysis workflow." }); // Limit text length const MAX_TEXT_LENGTH = 20000; // Consider limits for OpenAI context window const truncatedText = documentText.substring(0, MAX_TEXT_LENGTH); if (documentText.length > MAX_TEXT_LENGTH) { // --- Steps 2, 3, 4, 5 (Analysis, Extraction, Traversal, Final Output) --- log.push({ agent: "System", type: "step", message: "Starting Content Analysis..." }); const analysisResponse = await callOpenAI(openai, contentAnalysisSystemPrompt, truncatedText, "gpt-4o", true); let analysisResult: AnalysisResult | null = null; if (analysisResponse.role === "assistant" && typeof analysisResponse.content === "object") { log.push({ agent: "System", type: "step", message: "Starting Citation Extraction..." }); const citationResponse = await callOpenAI(openai, citationExtractionSystemPrompt, truncatedText, "gpt-4o", true); let extractedCitations: Citation[] = []; if (
// =============================================================================import { OpenAI } from "https://esm.town/v/std/openai";// import { Request, Response } from "https://esm.town/v/std/fetch"; // Usually global}interface OpenAIResponse { races: RaceInfo[];}// --- ***** THIS FUNCTION WAS MISSING ***** ---// --- OpenAI Generation Function ---// Asynchronously fetches race data from OpenAI's Chat Completion API.async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> { let openai; try { // IMPORTANT: Ensure the 'openai' secret is configured in your Val Town settings. openai = new OpenAI(); } catch (error) { console.error("Failed to initialize OpenAI client. Check 'openai' secret in Val Town.", error); console.warn("Using fallback race data due to OpenAI initialization error."); return fallbackRaceData; } try { console.info("Requesting race data generation from OpenAI..."); const completion = await openai.chat.completions.create({ model: "gpt-4o", // Or "gpt-3.5-turbo" messages: [{ role: "user", content: prompt }], const rawContent = completion.choices[0]?.message?.content; if (!rawContent) { throw new Error("OpenAI returned an empty response message."); } console.info("Received response from OpenAI. Parsing and validating JSON..."); let parsedJson; try { parsedJson = JSON.parse(rawContent); } catch (parseError) { console.error("Failed to parse OpenAI response as JSON:", rawContent); throw new Error("Invalid JSON received from OpenAI."); } ) ) { console.warn("OpenAI response JSON failed validation:", parsedJson); throw new Error("OpenAI response JSON does not match expected structure/data."); } const generatedData = (parsedJson as OpenAIResponse).races; console.info(`Successfully generated and validated ${generatedData.length} races from OpenAI.`); // Trim whitespace just in case return generatedData.map(race => ({ })); } catch (error) { console.error("Error fetching or processing data from OpenAI:", error); if (error.constructor.name === "AuthenticationError") { console.error("OpenAI Authentication Error: Check 'openai' secret."); } // Add more specific error checks if needed console.warn("Using fallback race data due to the error."); // 1. Fetch Race Data - Ensure this line is calling the function defined above console.log("Attempting to fetch race data..."); const activeRaceData = await generateRaceDataWithOpenAI(); console.log(`Workspaceed ${activeRaceData.length} races. First race: ${activeRaceData[0]?.name || "N/A"}`);
// =============================================================================import { OpenAI } from "https://esm.town/v/std/openai";// import { Request, Response } from "https://esm.town/v/std/fetch"; // Usually global}interface OpenAIResponse { races: RaceInfo[];}];async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> { let openai; try { openai = new OpenAI(); // Ensure 'openai' secret is set in Val Town } catch (error) { console.error("Failed to initialize OpenAI client.", error); return fallbackRaceData; } const prompt = `{Your OpenAI prompt from previous version - unchanged}`; // Keep the prompt as before try { console.info("Requesting race data from OpenAI..."); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "user", content: prompt }], }); const rawContent = completion.choices[0]?.message?.content; if (!rawContent) throw new Error("OpenAI returned empty content."); console.info("Parsing and validating OpenAI response..."); let parsedJson = JSON.parse(rawContent); || parsedJson.races.some(/*... detailed item checks ...*/) ) { throw new Error("OpenAI response JSON failed validation."); } const generatedData = (parsedJson as OpenAIResponse).races; console.info(`Successfully validated ${generatedData.length} races from OpenAI.`); return generatedData.map(race => ({ ...race, name: race.name.trim() /* etc */ })); } catch (error) { console.error("Error fetching/processing from OpenAI:", error); return fallbackRaceData; }// =============================================================================export default async function server(request: Request): Promise<Response> { const activeRaceData = await generateRaceDataWithOpenAI(); const css = `
// =============================================================================// Import OpenAI library from Val Town's standard modules// Ensure you have the 'openai' secret set in your Val Town account.import { OpenAI } from "https://esm.town/v/std/openai";// Import Request and Response types if needed (usually available globally in Val Town)// Example: import { Request, Response } from "https://esm.town/v/std/fetch";}// Defines the specific JSON structure expected back from the OpenAI APIinterface OpenAIResponse { races: RaceInfo[]; // An array containing the race information}// --- Fallback Data ---// Provides default race data if the OpenAI API call fails or returns invalid data.const fallbackRaceData: RaceInfo[] = [ {];// --- OpenAI Generation Function ---// Asynchronously fetches race data from OpenAI's Chat Completion API.async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> { // Initialize the OpenAI client (using API key from Val Town secrets) // Ensure the 'openai' secret is configured in your Val Town settings. let openai; try { openai = new OpenAI(); } catch (error) { console.error("Failed to initialize OpenAI client. Check 'openai' secret in Val Town.", error); console.warn("Using fallback race data due to OpenAI initialization error."); return fallbackRaceData; } // Detailed prompt instructing OpenAI to generate race data in a specific JSON format. const prompt = ` Generate a list of exactly 4 distinct fantasy character races suitable for an RPG character creator carousel. try { console.info("Requesting race data generation from OpenAI..."); const completion = await openai.chat.completions.create({ model: "gpt-4o", // Recommended model messages: [{ role: "user", content: prompt }], const rawContent = completion.choices[0]?.message?.content; if (!rawContent) { throw new Error("OpenAI returned an empty response message."); } // console.debug("Raw OpenAI Response:", rawContent); // Uncomment for debugging console.info("Received response from OpenAI. Parsing and validating JSON..."); let parsedJson; try { parsedJson = JSON.parse(rawContent); } catch (parseError) { console.error("Failed to parse OpenAI response as JSON:", rawContent); throw new Error("Invalid JSON received from OpenAI."); } ) ) { console.warn("OpenAI response JSON failed validation:", parsedJson); throw new Error( "OpenAI response JSON does not match the expected structure or contains invalid data.", ); } // Type assertion after successful validation const generatedData = (parsedJson as OpenAIResponse).races; console.info(`Successfully generated and validated ${generatedData.length} races from OpenAI.`); // Sanitize potentially empty strings just in case validation missed something edge-casey (unlikely with checks above) return generatedData.map(race => ({ })); } catch (error) { // Log the specific error encountered during the OpenAI call or processing console.error("Error fetching or processing data from OpenAI:", error); // Check if the error is specifically an AuthenticationError if (error.constructor.name === "AuthenticationError") { console.error( "OpenAI Authentication Error: Please ensure your 'openai' secret is correctly configured in Val Town settings.", ); } else if (error instanceof SyntaxError) { console.error("JSON Parsing Error: The response from OpenAI was not valid JSON."); } else { // General error console.error("An unexpected error occurred while communicating with OpenAI."); } console.warn("Using fallback race data due to the error.");// This function handles incoming HTTP requests and returns the HTML for the game.export default async function server(request: Request): Promise<Response> { // 1. Fetch Race Data: Attempt to get dynamic data from OpenAI, use fallback on error. const activeRaceData = await generateRaceDataWithOpenAI(); // 2. Define CSS Styles: Includes base carousel, new game UI, and enhanced effects.
// Val Town Script: Dynamic Character Race Carousel with OpenAI// =============================================================================// =============================================================================// Import OpenAI library from Val Town's standard modules// Ensure you have the 'openai' secret set in your Val Town account.// Alternatives: import { OpenAI } from "npm:openai";import { OpenAI } from "https://esm.town/v/std/openai";// --- Define Expected Data Structures ---}// Defines the specific JSON structure expected back from the OpenAI APIinterface OpenAIResponse { races: RaceInfo[]; // An array containing the race information}// --- Fallback Data ---// Provides default race data if the OpenAI API call fails or returns invalid data.// This ensures the carousel always has content to display.const fallbackRaceData: RaceInfo[] = [];// --- OpenAI Generation Function ---// Asynchronously fetches race data from OpenAI's Chat Completion API.async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> { // Initialize the OpenAI client (using API key from Val Town secrets) const openai = new OpenAI(); // Detailed prompt instructing OpenAI to generate race data in a specific JSON format. const prompt = ` Generate a list of exactly 4 distinct fantasy character races suitable for an RPG character creator carousel. try { console.info("Requesting race data generation from OpenAI..."); const completion = await openai.chat.completions.create({ model: "gpt-4o", // Recommended model, can use "gpt-3.5-turbo" as a fallback messages: [{ role: "user", content: prompt }], // Force OpenAI to return JSON matching the structure described in the prompt response_format: { type: "json_object" }, temperature: 0.8, // Balances creativity and consistency const rawContent = completion.choices[0]?.message?.content; if (!rawContent) { throw new Error("OpenAI returned an empty response message."); } // console.debug("Raw OpenAI Response:", rawContent); // Uncomment for deep debugging console.info("Received response from OpenAI. Parsing and validating JSON..."); const parsedJson = JSON.parse(rawContent); // --- Rigorous Validation --- // Check if the parsed response conforms to the expected OpenAIResponse structure. if ( typeof parsedJson !== "object" // Must be an object ) ) { console.warn("OpenAI response JSON failed validation:", parsedJson); throw new Error( "OpenAI response JSON does not match the expected structure or contains invalid data types/formats.", ); } // Type assertion after successful validation const generatedData = (parsedJson as OpenAIResponse).races; console.info(`Successfully generated and validated ${generatedData.length} races from OpenAI.`); return generatedData; } catch (error) { console.error("Error fetching or processing data from OpenAI:", error); console.warn("Using fallback race data due to the error."); return fallbackRaceData; // Return default data on any failure// This function handles incoming HTTP requests and returns an HTML response.export default async function server(request: Request): Promise<Response> { // 1. Fetch Race Data: Attempt to get dynamic data from OpenAI, use fallback on error. const activeRaceData = await generateRaceDataWithOpenAI(); // 2. Define CSS Styles: Static CSS for the carousel appearance and animations. // --- Injected Data --- // This 'raceData' variable receives the array generated by the server (OpenAI or fallback). // It's crucial that this data is valid JSON when the script runs. const raceData = ${JSON.stringify(activeRaceData, null, 2)}; // Pretty-print for readability in source
* and their relationships (citations, references), visualizing them as a network graph. * Runs entirely within a single Val Town endpoint. * Uses React Flow for visualization and OpenAI for analysis. * * Structure adapted from the Multi-Agent AI Support Simulation example.// --- Main Server Request Handler (Val Town Entry Point) ---export default async function(req: Request): Promise<Response> { // --- Dynamic Import of OpenAI Library --- const { OpenAI } = await import("https://esm.town/v/std/openai"); // Server-side logging utility } // --- OpenAI Initialization --- let openai: OpenAI; try { // Assumes OPENAI_API_KEY is set as a Val Town secret named 'openai' openai = new OpenAI(); // Perform a simple test call or validation if needed, but often just instantiating is enough. } catch (e: any) { logServer("ERROR", "Failed to initialize OpenAI Client", { error: e.message }); // If OpenAI fails to init, we can still potentially serve the HTML, // but API calls will fail later. For API calls, we return an immediate error. // We'll handle API call errors within the analysis function. } // Check if OpenAI client initialized successfully *before* making the call if (!openai) { return { success: false, error: "OpenAI client failed to initialize. Check server logs and API key configuration.", }; } try { const completion = await openai.chat.completions.create({ model: "gpt-4o", // Recommend powerful model for this task response_format: { type: "json_object" }, logServer("ERROR", "Policy Analysis tool execution failed", { errorMessage: error.message, stack: error.stack }); let specificError = error.message; // Check for common OpenAI API errors if (error.status === 401) specificError = "OpenAI Authentication failed. Check API key secret."; if (error.status === 429) specificError = "OpenAI Rate limit or quota exceeded."; if (error.status >= 500) specificError = "OpenAI server error. Please try again later."; return { success: false, error: `Analysis failed: \${specificError}` }; try { // --- Check OpenAI init status again specifically for API calls --- if (!openai) { throw new Error("OpenAI client is not available. Check server configuration/secrets."); }
// Val Town Script: Dynamic Character Race Carousel with OpenAI// Import the OpenAI library (ensure you have the 'openai' secret set in Val Town)import { OpenAI } from "https://esm.town/v/std/openai"; // Or use 'npm:openai' or 'std/openai'// --- Define Expected Data Structures ---}// Define the specific JSON structure we expect OpenAI to returninterface OpenAIResponse { races: RaceInfo[];}// --- Fallback Data ---// Used if OpenAI call fails or returns invalid dataconst fallbackRaceData: RaceInfo[] = [ {];// --- OpenAI Generation Function ---async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> { // Use 'new OpenAI()' if using std/openai const openai = new OpenAI(); // Updated prompt requesting a specific JSON object structure try { console.info("Calling OpenAI to generate race data..."); const completion = await openai.chat.completions.create({ model: "gpt-4o", // Or "gpt-3.5-turbo" messages: [{ role: "user", content: prompt }], const content = completion.choices[0]?.message?.content; if (!content) { throw new Error("OpenAI returned an empty response content."); } console.info("Received response from OpenAI. Parsing JSON..."); const parsedJson = JSON.parse(content); ) ) { throw new Error("OpenAI response JSON does not match the expected structure or contains invalid data."); } const generatedData = (parsedJson as OpenAIResponse).races; console.info(`Successfully generated and validated ${generatedData.length} races.`); return generatedData; } catch (error) { console.error("Error fetching or processing data from OpenAI:", error); console.warn("Using fallback race data due to error."); return fallbackRaceData;// --- Main HTTP Handler (Val Town Entry Point) ---export default async function server(request: Request): Promise<Response> { // 1. Generate race data using OpenAI (or use fallback on error) const activeRaceData = await generateRaceDataWithOpenAI(); // 2. Define CSS (remains static) // Inject the dynamically generated data from the server // This 'raceData' variable will hold the array from OpenAI or the fallback const raceData = ${JSON.stringify(activeRaceData, null, 2)};
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" },
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" },
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