6* Uses 'npm:pdf.js-extract' for direct PDF text extraction.
7* Serves HTML UI & API endpoint from the same Val.
8* OpenAI import is dynamically done inside the main server function.
9*
10* Based on structure from multi-agent support simulation example.
11* Assumes 'openai' secret is set in Val Town environment variables.
12*
13* Last Updated: 2025-05-01 (Dashboard UI, Localization, Animation Integration)
950export default async function(req: Request) {
951// --- Dynamic Imports (Inside Handler) ---
952const { OpenAI } = await import("https://esm.town/v/std/openai");
953const { z } = await import("npm:zod");
954const { fetch } = await import("https://esm.town/v/std/fetch");
990}
991992// --- Helper Function: Call OpenAI API (Unchanged) ---
993async function callOpenAI(
994openai: OpenAI,
995systemPrompt: string,
996userMessage: string,
999): Promise<{ role: "assistant" | "system"; content: string | object }> {
1000try {
1001const response = await openai.chat.completions.create({
1002model: model,
1003messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }],
1011return { role: "assistant", content: JSON.parse(content) };
1012} catch (parseError) {
1013console.error("OpenAI JSON Parse Error:", parseError, "Raw Content:", content);
1014throw new Error(`AI response was not valid JSON. Raw: ${content.substring(0, 150)}...`);
1015}
1016} else { return { role: "assistant", content: content }; }
1017} catch (error) {
1018console.error(`OpenAI API call failed. ExpectJSON: ${expectJson}. Error:`, error);
1019let errorMessage = "Error communicating with AI model.";
1020if (error.message) { errorMessage += ` Details: ${error.message}`; }
1021// Check for specific error types if needed (e.g., rate limits, auth)
1022if (error.status === 401) errorMessage = "Authentication error with OpenAI API. Check your secret key.";
1023if (error.status === 429) errorMessage = "OpenAI API rate limit exceeded. Please try again later.";
10241025return { role: "system", content: errorMessage };
1112log: LogEntry[],
1113): Promise<LogEntry[]> { // Returns the completed log array
1114const openai = new OpenAI(); // Assumes API key is in environment variables
11151116log.push({ agent: "System", type: "step", message: "Starting analysis workflow." });
1217// --- 2. Content Analysis ---
1218log.push({ agent: "System", type: "step", message: "Starting Content Analysis..." });
1219const analysisResponse = await callOpenAI(openai, contentAnalysisSystemPrompt, truncatedText, "gpt-4o", true); // Use gpt-4o
1220let analysisResult: AnalysisResult | null = null;
1221if (analysisResponse.role === "assistant" && typeof analysisResponse.content === "object") {
1237// --- 3. Citation Extraction ---
1238log.push({ agent: "System", type: "step", message: "Starting Citation Extraction..." });
1239const citationResponse = await callOpenAI(openai, citationExtractionSystemPrompt, truncatedText, "gpt-4o", true); // Use gpt-4o
1240let extractedCitations: Citation[] = [];
1241if (
1267message: \`AI response was not the expected JSON format. Received: \${JSON.stringify(citationResponse.content).substring(0, 200)}...\`,
1268});
1269} else { // System error from callOpenAI
1270log.push({ agent: "Citation Extraction Agent", type: "error", message: citationResponse.content });
1271}
myanythingmain.tsx3 matches
125if (request.method === 'POST') {
126try {
127const { OpenAI } = await import("https://esm.town/v/std/openai");
128const openai = new OpenAI();
129130const formData = await request.formData();
138const cvText = new TextDecoder().decode(cvBuffer);
139140const completion = await openai.chat.completions.create({
141messages: [
142{
myeverythingmain.tsx3 matches
125if (request.method === "POST") {
126try {
127const { OpenAI } = await import("https://esm.town/v/std/openai");
128const openai = new OpenAI();
129130const formData = await request.formData();
138const cvText = new TextDecoder().decode(cvBuffer);
139140const completion = await openai.chat.completions.create({
141messages: [
142{
125if (request.method === "POST") {
126try {
127const { OpenAI } = await import("https://esm.town/v/std/openai");
128const openai = new OpenAI();
129130const formData = await request.formData();
138const cvText = new TextDecoder().decode(cvBuffer);
139140const completion = await openai.chat.completions.create({
141messages: [
142{
197const [isInitialized, setIsInitialized] = useState(false);
198199// --- OpenAI Interaction (Unchanged) ---
200// !!! IMPORTANT SECURITY WARNING & Val Town Note !!!
201// ... (same as before)
205if (!text) return;
206setStatus("Sending to AI...");
207console.log("Sending to OpenAI:", text);
208setAiResponse(""); // Clear previous response
209setError(null);
213try {
214// ---- START: Replace this block in Val Town ----
215const response = await fetch("https://api.openai.com/v1/chat/completions", {
216method: "POST",
217headers: {
226const errorData = await response.json().catch(() => ({})); // Try to get JSON error details
227throw new Error(
228`OpenAI API Error: ${response.status} ${response.statusText} - ${
229errorData?.error?.message ?? "Check API key or usage limits."
230}`,
240speakText(reply);
241} catch (err: any) {
242console.error("OpenAI call failed:", err);
243const errMsg = `AI Error: ${err.message}`;
244setError(errMsg);
FixItWandgenerate.ts6 matches
1import OpenAI from "https://esm.sh/openai@4.96.0";
2import { search } from "./locations/mod.ts";
34const openai = new OpenAI();
56/**
39const audioFile = new File([audioBlob], "a.mp3", { type: "audio/mp3" });
4041transcription = await openai.audio.transcriptions.create({
42file: audioFile,
43model: "whisper-1",
50if (transcription) {
51// Detect possible location references in the transcription
52const locationDetectionResponse = await openai.chat.completions.create({
53model: "gpt-4o-mini",
54messages: [
149});
150151const chatResponse = await openai.chat.completions.create({
152model: "gpt-4o",
153messages: messages as any, // Type assertion to fix any TypeScript issues
166`;
167168const subjectResponse = await openai.chat.completions.create({
169model: "gpt-4o-mini",
170messages: [
OpenTownie_jacksonsystem_prompt.txt4 matches
88Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.
8990### OpenAI
9192```ts
93import { OpenAI } from "https://esm.town/v/std/openai";
94const openai = new OpenAI();
95const completion = await openai.chat.completions.create({
96messages: [
97{ role: "user", content: "Say hello in a creative way" },
1// Val Town Script: Dynamic Character Race Carousel with OpenAI + Plane Tilt + Fanning Cards + Animated Borders
23// =============================================================================
5// =============================================================================
67// Import OpenAI library from Val Town's standard modules
8import { OpenAI } from "https://esm.town/v/std/openai"; // Ensure 'openai' secret is set
910// --- Configuration ---
21borderAnimationHint?: string; // <<< NEW: Optional hint for border style
22}
23interface OpenAIResponse {
24races: RaceInfo[];
25}
65];
6667// --- OpenAI Generation Function ---
68async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> {
69const openai = new OpenAI();
70const numToRequest = Math.max(1, NUM_CARDS_TO_GENERATE);
71const prompt = `
8182try {
83console.info(`Requesting ${numToRequest} race data generation from OpenAI...`);
84const completion = await openai.chat.completions.create({
85model: "gpt-4o", // Or your preferred model
86messages: [{ role: "user", content: prompt }],
9091const rawContent = completion.choices[0]?.message?.content;
92if (!rawContent) throw new Error("OpenAI returned an empty response message.");
93console.info("Received response from OpenAI. Parsing and validating JSON...");
94const parsedJson = JSON.parse(rawContent);
95109)
110) {
111console.warn(`OpenAI response JSON failed validation for ${numToRequest} races:`, parsedJson);
112throw new Error("OpenAI response JSON structure, count, data types, or hint value invalid.");
113}
114115const generatedData = (parsedJson as OpenAIResponse).races.map(race => ({
116...race,
117// Ensure borderAnimationHint defaults to 'none' if missing from response
119}));
120121console.info(`Successfully generated and validated ${generatedData.length} races from OpenAI.`);
122return generatedData;
123} catch (error) {
124console.error("Error fetching or processing data from OpenAI:", error);
125console.warn("Using fallback race data due to the error.");
126// Ensure fallback data also has the hint, slice correctly
134// --- Main HTTP Handler (Val Town Entry Point) ---
135export default async function server(request: Request): Promise<Response> {
136const activeRaceData = await generateRaceDataWithOpenAI();
137138// Define CSS Styles
7* Serves HTML UI & API endpoint from the same Val.
8* Based on user-provided glassmorphism UI example.
9* Assumes 'openai' secret is set in Val Town environment variables.
10*
11* Last Updated: 2025-05-01 (Reference Relevance & Paradigmatic Analysis Integration)
916export default async function(req: Request) {
917// --- Dynamic Imports (Inside Handler) ---
918const { OpenAI } = await import("https://esm.town/v/std/openai");
919const { z } = await import("npm:zod");
920const { fetch } = await import("https://esm.town/v/std/fetch");
944}
945946// --- Helper Function: Call OpenAI API (Unchanged) ---
947async function callOpenAI(
948openai: OpenAI,
949systemPrompt: string,
950userMessage: string,
953): Promise<{ role: "assistant" | "system"; content: string | object }> {
954try {
955const response = await openai.chat.completions.create({
956model,
957messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }],
971else { return { role: "assistant", content }; }
972} catch (error) {
973console.error(`OpenAI call failed (ExpectJSON: ${expectJson}):`, error);
974let msg = "Error communicating with AI.";
975if (error.message) msg += ` Details: ${error.message}`;
976if (error.status === 401) msg = "OpenAI Auth Error.";
977if (error.status === 429) msg = "OpenAI Rate Limit Exceeded.";
978return { role: "system", content: msg };
979}
1042log: LogEntry[],
1043): Promise<LogEntry[]> {
1044const openai = new OpenAI();
1045log.push({ agent: "System", type: "step", message: "Workflow started." });
1046log.push({
1115// --- Content Analysis (Unchanged) ---
1116log.push({ agent: "System", type: "step", message: "Analyzing content..." });
1117const anaRes = await callOpenAI(openai, contentAnalysisSystemPrompt, truncText, "gpt-4o", true);
1118if (anaRes.role === "assistant" && anaRes.content && (anaRes.content as AnalysisResult).summary) { // Type assertion for check
1119log.push({ agent: "Content Analysis Agent", type: "result", message: anaRes.content });
1124// --- NEW: Paradigmatic Analysis ---
1125log.push({ agent: "System", type: "step", message: "Analyzing document context/paradigm..." });
1126const paradigmRes = await callOpenAI(openai, paradigmaticAnalysisSystemPrompt, truncText, "gpt-4o", true);
1127if (
1128paradigmRes.role === "assistant" && paradigmRes.content && (paradigmRes.content as ParadigmaticInfo).documentType
1135// --- MODIFIED: Reference Extraction ---
1136log.push({ agent: "System", type: "step", message: "Extracting references..." });
1137const refRes = await callOpenAI(openai, referenceExtractionSystemPrompt, truncText, "gpt-4o", true); // Use updated prompt
1138let extRef: Reference[] = []; // Use Reference type
1139// Check the correct key 'references' from the prompt
2* Multi-Agent Policy Document Analysis (Single Val Version with PDF Upload & Dashboard Style)
3* Demonstrates document ingestion (URL, Text, PDF Upload), content analysis,
4* citation extraction, and basic reference traversal using collaborative AI agents via OpenAI.
5* Uses 'npm:pdf.js-extract' for direct PDF text extraction within the Val (experimental).
6* Serves an HTML UI with a dashboard grid background and handles API requests within the same Val.
7* OpenAI import is dynamically done inside the main server function.
8*
9* Based on structure from multi-agent support simulation example.
10* Assumes 'openai' secret is set in Val Town environment variables.
11*
12* Last Updated: 2025-05-01 (Added PDF upload, dashboard style)
171<p class="description">
172Enter a document URL, paste text, or upload a PDF below. AI agents will analyze content, extract citations, and attempt reference traversal.<br>
173Uses OpenAI via Val Town & <code>npm:pdf.js-extract</code> for PDFs. Current Date: ${
174new Date().toLocaleDateString()
175}
339export default async function(req: Request) {
340// --- Dynamic Imports (Inside Handler) ---
341const { OpenAI } = await import("https://esm.town/v/std/openai");
342const { z } = await import("npm:zod");
343const { fetch } = await import("https://esm.town/v/std/fetch");
397}
398399// --- Helper Function: Call OpenAI API (Unchanged) ---
400async function callOpenAI(
401openai: OpenAI,
402systemPrompt: string,
403userMessage: string,
406): Promise<{ role: "assistant" | "system"; content: string | object }> {
407try {
408const response = await openai.chat.completions.create({
409model: model,
410messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }],
418return { role: "assistant", content: JSON.parse(content) };
419} catch (parseError) {
420console.error("OpenAI JSON Parse Error:", parseError, "Raw Content:", content);
421throw new Error(`AI response was not valid JSON. Raw: ${content.substring(0, 150)}...`);
422}
423} else { return { role: "assistant", content: content }; }
424} catch (error) {
425console.error(`OpenAI API call failed. ExpectJSON: ${expectJson}. Error:`, error);
426let errorMessage = "Error communicating with AI model.";
427if (error.message) { errorMessage += ` Details: ${error.message}`; }
486log: LogEntry[],
487): Promise<LogEntry[]> {
488const openai = new OpenAI();
489490log.push({ agent: "System", type: "step", message: "Starting analysis workflow." });
554555// Limit text length
556const MAX_TEXT_LENGTH = 20000; // Consider limits for OpenAI context window
557const truncatedText = documentText.substring(0, MAX_TEXT_LENGTH);
558if (documentText.length > MAX_TEXT_LENGTH) {
566// --- Steps 2, 3, 4, 5 (Analysis, Extraction, Traversal, Final Output) ---
567log.push({ agent: "System", type: "step", message: "Starting Content Analysis..." });
568const analysisResponse = await callOpenAI(openai, contentAnalysisSystemPrompt, truncatedText, "gpt-4o", true);
569let analysisResult: AnalysisResult | null = null;
570if (analysisResponse.role === "assistant" && typeof analysisResponse.content === "object") {
575576log.push({ agent: "System", type: "step", message: "Starting Citation Extraction..." });
577const citationResponse = await callOpenAI(openai, citationExtractionSystemPrompt, truncatedText, "gpt-4o", true);
578let extractedCitations: Citation[] = [];
579if (