Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/$%7Bart_info.art.src%7D?q=openai&page=7&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=openai

Returns an array of strings in format "username" or "username/projectName"

Found 1567 results for "openai"(938ms)

Pathwaymain.tsx15 matches

@Get•Updated 3 days ago
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">
172 Enter a document URL, paste text, or upload a PDF below. AI agents will analyze content, extract citations, and attempt reference traversal.<br>
173 Uses OpenAI via Val Town & <code>npm:pdf.js-extract</code> for PDFs. Current Date: ${
174 new Date().toLocaleDateString()
175 }
339export default async function(req: Request) {
340 // --- Dynamic Imports (Inside Handler) ---
341 const { OpenAI } = await import("https://esm.town/v/std/openai");
342 const { z } = await import("npm:zod");
343 const { fetch } = await import("https://esm.town/v/std/fetch");
397 }
398
399 // --- Helper Function: Call OpenAI API (Unchanged) ---
400 async function callOpenAI(
401 openai: OpenAI,
402 systemPrompt: string,
403 userMessage: string,
406 ): Promise<{ role: "assistant" | "system"; content: string | object }> {
407 try {
408 const response = await openai.chat.completions.create({
409 model: model,
410 messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }],
418 return { role: "assistant", content: JSON.parse(content) };
419 } catch (parseError) {
420 console.error("OpenAI JSON Parse Error:", parseError, "Raw Content:", content);
421 throw new Error(`AI response was not valid JSON. Raw: ${content.substring(0, 150)}...`);
422 }
423 } else { return { role: "assistant", content: content }; }
424 } catch (error) {
425 console.error(`OpenAI API call failed. ExpectJSON: ${expectJson}. Error:`, error);
426 let errorMessage = "Error communicating with AI model.";
427 if (error.message) { errorMessage += ` Details: ${error.message}`; }
486 log: LogEntry[],
487 ): Promise<LogEntry[]> {
488 const openai = new OpenAI();
489
490 log.push({ agent: "System", type: "step", message: "Starting analysis workflow." });
554
555 // Limit text length
556 const MAX_TEXT_LENGTH = 20000; // Consider limits for OpenAI context window
557 const truncatedText = documentText.substring(0, MAX_TEXT_LENGTH);
558 if (documentText.length > MAX_TEXT_LENGTH) {
566 // --- Steps 2, 3, 4, 5 (Analysis, Extraction, Traversal, Final Output) ---
567 log.push({ agent: "System", type: "step", message: "Starting Content Analysis..." });
568 const analysisResponse = await callOpenAI(openai, contentAnalysisSystemPrompt, truncatedText, "gpt-4o", true);
569 let analysisResult: AnalysisResult | null = null;
570 if (analysisResponse.role === "assistant" && typeof analysisResponse.content === "object") {
575
576 log.push({ agent: "System", type: "step", message: "Starting Citation Extraction..." });
577 const citationResponse = await callOpenAI(openai, citationExtractionSystemPrompt, truncatedText, "gpt-4o", true);
578 let extractedCitations: Citation[] = [];
579 if (

Test2main.tsx23 matches

@Get•Updated 3 days ago
5// =============================================================================
6
7import { OpenAI } from "https://esm.town/v/std/openai";
8// import { Request, Response } from "https://esm.town/v/std/fetch"; // Usually global
9
16}
17
18interface OpenAIResponse {
19 races: RaceInfo[];
20}
49
50// --- ***** THIS FUNCTION WAS MISSING ***** ---
51// --- OpenAI Generation Function ---
52// Asynchronously fetches race data from OpenAI's Chat Completion API.
53async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> {
54 let openai;
55 try {
56 // IMPORTANT: Ensure the 'openai' secret is configured in your Val Town settings.
57 openai = new OpenAI();
58 } catch (error) {
59 console.error("Failed to initialize OpenAI client. Check 'openai' secret in Val Town.", error);
60 console.warn("Using fallback race data due to OpenAI initialization error.");
61 return fallbackRaceData;
62 }
86
87 try {
88 console.info("Requesting race data generation from OpenAI...");
89 const completion = await openai.chat.completions.create({
90 model: "gpt-4o", // Or "gpt-3.5-turbo"
91 messages: [{ role: "user", content: prompt }],
96 const rawContent = completion.choices[0]?.message?.content;
97 if (!rawContent) {
98 throw new Error("OpenAI returned an empty response message.");
99 }
100 console.info("Received response from OpenAI. Parsing and validating JSON...");
101 let parsedJson;
102 try {
103 parsedJson = JSON.parse(rawContent);
104 } catch (parseError) {
105 console.error("Failed to parse OpenAI response as JSON:", rawContent);
106 throw new Error("Invalid JSON received from OpenAI.");
107 }
108
122 )
123 ) {
124 console.warn("OpenAI response JSON failed validation:", parsedJson);
125 throw new Error("OpenAI response JSON does not match expected structure/data.");
126 }
127
128 const generatedData = (parsedJson as OpenAIResponse).races;
129 console.info(`Successfully generated and validated ${generatedData.length} races from OpenAI.`);
130 // Trim whitespace just in case
131 return generatedData.map(race => ({
136 }));
137 } catch (error) {
138 console.error("Error fetching or processing data from OpenAI:", error);
139 if (error.constructor.name === "AuthenticationError") {
140 console.error("OpenAI Authentication Error: Check 'openai' secret.");
141 } // Add more specific error checks if needed
142 console.warn("Using fallback race data due to the error.");
154 // 1. Fetch Race Data - Ensure this line is calling the function defined above
155 console.log("Attempting to fetch race data...");
156 const activeRaceData = await generateRaceDataWithOpenAI();
157 console.log(`Workspaceed ${activeRaceData.length} races. First race: ${activeRaceData[0]?.name || "N/A"}`);
158

Story2main.tsx16 matches

@Get•Updated 3 days ago
5// =============================================================================
6
7import { OpenAI } from "https://esm.town/v/std/openai";
8// import { Request, Response } from "https://esm.town/v/std/fetch"; // Usually global
9
15}
16
17interface OpenAIResponse {
18 races: RaceInfo[];
19}
31];
32
33async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> {
34 let openai;
35 try {
36 openai = new OpenAI(); // Ensure 'openai' secret is set in Val Town
37 } catch (error) {
38 console.error("Failed to initialize OpenAI client.", error);
39 return fallbackRaceData;
40 }
41 const prompt = `{Your OpenAI prompt from previous version - unchanged}`; // Keep the prompt as before
42
43 try {
44 console.info("Requesting race data from OpenAI...");
45 const completion = await openai.chat.completions.create({
46 model: "gpt-4o",
47 messages: [{ role: "user", content: prompt }],
50 });
51 const rawContent = completion.choices[0]?.message?.content;
52 if (!rawContent) throw new Error("OpenAI returned empty content.");
53 console.info("Parsing and validating OpenAI response...");
54 let parsedJson = JSON.parse(rawContent);
55
59 || parsedJson.races.some(/*... detailed item checks ...*/)
60 ) {
61 throw new Error("OpenAI response JSON failed validation.");
62 }
63 const generatedData = (parsedJson as OpenAIResponse).races;
64 console.info(`Successfully validated ${generatedData.length} races from OpenAI.`);
65 return generatedData.map(race => ({ ...race, name: race.name.trim() /* etc */
66 }));
67 } catch (error) {
68 console.error("Error fetching/processing from OpenAI:", error);
69 return fallbackRaceData;
70 }
75// =============================================================================
76export default async function server(request: Request): Promise<Response> {
77 const activeRaceData = await generateRaceDataWithOpenAI();
78
79 const css = `

storymain.tsx34 matches

@Get•Updated 3 days ago
5// =============================================================================
6
7// Import OpenAI library from Val Town's standard modules
8// Ensure you have the 'openai' secret set in your Val Town account.
9import { OpenAI } from "https://esm.town/v/std/openai";
10// Import Request and Response types if needed (usually available globally in Val Town)
11// Example: import { Request, Response } from "https://esm.town/v/std/fetch";
21}
22
23// Defines the specific JSON structure expected back from the OpenAI API
24interface OpenAIResponse {
25 races: RaceInfo[]; // An array containing the race information
26}
27
28// --- Fallback Data ---
29// Provides default race data if the OpenAI API call fails or returns invalid data.
30const fallbackRaceData: RaceInfo[] = [
31 {
55];
56
57// --- OpenAI Generation Function ---
58// Asynchronously fetches race data from OpenAI's Chat Completion API.
59async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> {
60 // Initialize the OpenAI client (using API key from Val Town secrets)
61 // Ensure the 'openai' secret is configured in your Val Town settings.
62 let openai;
63 try {
64 openai = new OpenAI();
65 } catch (error) {
66 console.error("Failed to initialize OpenAI client. Check 'openai' secret in Val Town.", error);
67 console.warn("Using fallback race data due to OpenAI initialization error.");
68 return fallbackRaceData;
69 }
70
71 // Detailed prompt instructing OpenAI to generate race data in a specific JSON format.
72 const prompt = `
73 Generate a list of exactly 4 distinct fantasy character races suitable for an RPG character creator carousel.
94
95 try {
96 console.info("Requesting race data generation from OpenAI...");
97 const completion = await openai.chat.completions.create({
98 model: "gpt-4o", // Recommended model
99 messages: [{ role: "user", content: prompt }],
105 const rawContent = completion.choices[0]?.message?.content;
106 if (!rawContent) {
107 throw new Error("OpenAI returned an empty response message.");
108 }
109 // console.debug("Raw OpenAI Response:", rawContent); // Uncomment for debugging
110
111 console.info("Received response from OpenAI. Parsing and validating JSON...");
112 let parsedJson;
113 try {
114 parsedJson = JSON.parse(rawContent);
115 } catch (parseError) {
116 console.error("Failed to parse OpenAI response as JSON:", rawContent);
117 throw new Error("Invalid JSON received from OpenAI.");
118 }
119
133 )
134 ) {
135 console.warn("OpenAI response JSON failed validation:", parsedJson);
136 throw new Error(
137 "OpenAI response JSON does not match the expected structure or contains invalid data.",
138 );
139 }
140
141 // Type assertion after successful validation
142 const generatedData = (parsedJson as OpenAIResponse).races;
143
144 console.info(`Successfully generated and validated ${generatedData.length} races from OpenAI.`);
145 // Sanitize potentially empty strings just in case validation missed something edge-casey (unlikely with checks above)
146 return generatedData.map(race => ({
151 }));
152 } catch (error) {
153 // Log the specific error encountered during the OpenAI call or processing
154 console.error("Error fetching or processing data from OpenAI:", error);
155 // Check if the error is specifically an AuthenticationError
156 if (error.constructor.name === "AuthenticationError") {
157 console.error(
158 "OpenAI Authentication Error: Please ensure your 'openai' secret is correctly configured in Val Town settings.",
159 );
160 } else if (error instanceof SyntaxError) {
161 console.error("JSON Parsing Error: The response from OpenAI was not valid JSON.");
162 } else {
163 // General error
164 console.error("An unexpected error occurred while communicating with OpenAI.");
165 }
166 console.warn("Using fallback race data due to the error.");
176// This function handles incoming HTTP requests and returns the HTML for the game.
177export default async function server(request: Request): Promise<Response> {
178 // 1. Fetch Race Data: Attempt to get dynamic data from OpenAI, use fallback on error.
179 const activeRaceData = await generateRaceDataWithOpenAI();
180
181 // 2. Define CSS Styles: Includes base carousel, new game UI, and enhanced effects.

guidemain.tsx29 matches

@Get•Updated 3 days ago
1// Val Town Script: Dynamic Character Race Carousel with OpenAI
2
3// =============================================================================
5// =============================================================================
6
7// Import OpenAI library from Val Town's standard modules
8// Ensure you have the 'openai' secret set in your Val Town account.
9// Alternatives: import { OpenAI } from "npm:openai";
10import { OpenAI } from "https://esm.town/v/std/openai";
11
12// --- Define Expected Data Structures ---
20}
21
22// Defines the specific JSON structure expected back from the OpenAI API
23interface OpenAIResponse {
24 races: RaceInfo[]; // An array containing the race information
25}
26
27// --- Fallback Data ---
28// Provides default race data if the OpenAI API call fails or returns invalid data.
29// This ensures the carousel always has content to display.
30const fallbackRaceData: RaceInfo[] = [
58];
59
60// --- OpenAI Generation Function ---
61// Asynchronously fetches race data from OpenAI's Chat Completion API.
62async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> {
63 // Initialize the OpenAI client (using API key from Val Town secrets)
64 const openai = new OpenAI();
65
66 // Detailed prompt instructing OpenAI to generate race data in a specific JSON format.
67 const prompt = `
68 Generate a list of exactly 4 distinct fantasy character races suitable for an RPG character creator carousel.
89
90 try {
91 console.info("Requesting race data generation from OpenAI...");
92 const completion = await openai.chat.completions.create({
93 model: "gpt-4o", // Recommended model, can use "gpt-3.5-turbo" as a fallback
94 messages: [{ role: "user", content: prompt }],
95 // Force OpenAI to return JSON matching the structure described in the prompt
96 response_format: { type: "json_object" },
97 temperature: 0.8, // Balances creativity and consistency
101 const rawContent = completion.choices[0]?.message?.content;
102 if (!rawContent) {
103 throw new Error("OpenAI returned an empty response message.");
104 }
105 // console.debug("Raw OpenAI Response:", rawContent); // Uncomment for deep debugging
106
107 console.info("Received response from OpenAI. Parsing and validating JSON...");
108 const parsedJson = JSON.parse(rawContent);
109
110 // --- Rigorous Validation ---
111 // Check if the parsed response conforms to the expected OpenAIResponse structure.
112 if (
113 typeof parsedJson !== "object" // Must be an object
125 )
126 ) {
127 console.warn("OpenAI response JSON failed validation:", parsedJson);
128 throw new Error(
129 "OpenAI response JSON does not match the expected structure or contains invalid data types/formats.",
130 );
131 }
132
133 // Type assertion after successful validation
134 const generatedData = (parsedJson as OpenAIResponse).races;
135
136 console.info(`Successfully generated and validated ${generatedData.length} races from OpenAI.`);
137 return generatedData;
138 } catch (error) {
139 console.error("Error fetching or processing data from OpenAI:", error);
140 console.warn("Using fallback race data due to the error.");
141 return fallbackRaceData; // Return default data on any failure
146// This function handles incoming HTTP requests and returns an HTML response.
147export default async function server(request: Request): Promise<Response> {
148 // 1. Fetch Race Data: Attempt to get dynamic data from OpenAI, use fallback on error.
149 const activeRaceData = await generateRaceDataWithOpenAI();
150
151 // 2. Define CSS Styles: Static CSS for the carousel appearance and animations.
379
380 // --- Injected Data ---
381 // This 'raceData' variable receives the array generated by the server (OpenAI or fallback).
382 // It's crucial that this data is valid JSON when the script runs.
383 const raceData = ${JSON.stringify(activeRaceData, null, 2)}; // Pretty-print for readability in source

politymain.tsx20 matches

@salon•Updated 3 days ago
4 * and their relationships (citations, references), visualizing them as a network graph.
5 * Runs entirely within a single Val Town endpoint.
6 * Uses React Flow for visualization and OpenAI for analysis.
7 *
8 * Structure adapted from the Multi-Agent AI Support Simulation example.
934// --- Main Server Request Handler (Val Town Entry Point) ---
935export default async function(req: Request): Promise<Response> {
936 // --- Dynamic Import of OpenAI Library ---
937 const { OpenAI } = await import("https://esm.town/v/std/openai");
938
939 // Server-side logging utility
943 }
944
945 // --- OpenAI Initialization ---
946 let openai: OpenAI;
947 try {
948 // Assumes OPENAI_API_KEY is set as a Val Town secret named 'openai'
949 openai = new OpenAI();
950 // Perform a simple test call or validation if needed, but often just instantiating is enough.
951 } catch (e: any) {
952 logServer("ERROR", "Failed to initialize OpenAI Client", { error: e.message });
953 // If OpenAI fails to init, we can still potentially serve the HTML,
954 // but API calls will fail later. For API calls, we return an immediate error.
955 // We'll handle API call errors within the analysis function.
970 }
971
972 // Check if OpenAI client initialized successfully *before* making the call
973 if (!openai) {
974 return {
975 success: false,
976 error: "OpenAI client failed to initialize. Check server logs and API key configuration.",
977 };
978 }
1018
1019 try {
1020 const completion = await openai.chat.completions.create({
1021 model: "gpt-4o", // Recommend powerful model for this task
1022 response_format: { type: "json_object" },
1079 logServer("ERROR", "Policy Analysis tool execution failed", { errorMessage: error.message, stack: error.stack });
1080 let specificError = error.message;
1081 // Check for common OpenAI API errors
1082 if (error.status === 401) specificError = "OpenAI Authentication failed. Check API key secret.";
1083 if (error.status === 429) specificError = "OpenAI Rate limit or quota exceeded.";
1084 if (error.status >= 500) specificError = "OpenAI server error. Please try again later.";
1085
1086 return { success: false, error: `Analysis failed: \${specificError}` };
1100
1101 try {
1102 // --- Check OpenAI init status again specifically for API calls ---
1103 if (!openai) {
1104 throw new Error("OpenAI client is not available. Check server configuration/secrets.");
1105 }
1106

faithfulTanEelmain.tsx20 matches

@salon•Updated 3 days ago
1// Val Town Script: Dynamic Character Race Carousel with OpenAI
2
3// Import the OpenAI library (ensure you have the 'openai' secret set in Val Town)
4import { OpenAI } from "https://esm.town/v/std/openai"; // Or use 'npm:openai' or 'std/openai'
5
6// --- Define Expected Data Structures ---
13}
14
15// Define the specific JSON structure we expect OpenAI to return
16interface OpenAIResponse {
17 races: RaceInfo[];
18}
19
20// --- Fallback Data ---
21// Used if OpenAI call fails or returns invalid data
22const fallbackRaceData: RaceInfo[] = [
23 {
47];
48
49// --- OpenAI Generation Function ---
50async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> {
51 // Use 'new OpenAI()' if using std/openai
52 const openai = new OpenAI();
53
54 // Updated prompt requesting a specific JSON object structure
70
71 try {
72 console.info("Calling OpenAI to generate race data...");
73 const completion = await openai.chat.completions.create({
74 model: "gpt-4o", // Or "gpt-3.5-turbo"
75 messages: [{ role: "user", content: prompt }],
81 const content = completion.choices[0]?.message?.content;
82 if (!content) {
83 throw new Error("OpenAI returned an empty response content.");
84 }
85
86 console.info("Received response from OpenAI. Parsing JSON...");
87 const parsedJson = JSON.parse(content);
88
101 )
102 ) {
103 throw new Error("OpenAI response JSON does not match the expected structure or contains invalid data.");
104 }
105
106 const generatedData = (parsedJson as OpenAIResponse).races;
107
108 console.info(`Successfully generated and validated ${generatedData.length} races.`);
109 return generatedData;
110 } catch (error) {
111 console.error("Error fetching or processing data from OpenAI:", error);
112 console.warn("Using fallback race data due to error.");
113 return fallbackRaceData;
117// --- Main HTTP Handler (Val Town Entry Point) ---
118export default async function server(request: Request): Promise<Response> {
119 // 1. Generate race data using OpenAI (or use fallback on error)
120 const activeRaceData = await generateRaceDataWithOpenAI();
121
122 // 2. Define CSS (remains static)
165
166 // Inject the dynamically generated data from the server
167 // This 'raceData' variable will hold the array from OpenAI or the fallback
168 const raceData = ${JSON.stringify(activeRaceData, null, 2)};
169

stevensDemo.cursorrules4 matches

@yyl•Updated 3 days ago
100Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.
101
102### OpenAI
103```ts
104import { OpenAI } from "https://esm.town/v/std/openai";
105const openai = new OpenAI();
106const completion = await openai.chat.completions.create({
107 messages: [
108 { role: "user", content: "Say hello in a creative way" },

stevensDemo.cursorrules4 matches

@maartenpo•Updated 4 days ago
100Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.
101
102### OpenAI
103```ts
104import { OpenAI } from "https://esm.town/v/std/openai";
105const openai = new OpenAI();
106const completion = await openai.chat.completions.create({
107 messages: [
108 { role: "user", content: "Say hello in a creative way" },

strategistmain.tsx3 matches

@omar1•Updated 4 days ago
276export default async function server(request: Request): Promise<Response> {
277 if (request.method === "POST" && new URL(request.url).pathname === "/generate-plan") {
278 const { OpenAI } = await import("https://esm.town/v/std/openai");
279 const openai = new OpenAI();
280
281 const { context } = await request.json();
282
283 const completion = await openai.chat.completions.create({
284 model: "gpt-4o-mini",
285 messages: [

testOpenAI1 file match

@shouser•Updated 1 day ago

testOpenAI1 file match

@stevekrouse•Updated 1 day ago
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": "*",