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/$%7Bsuccess?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 1573 results for "openai"(703ms)

feedbackmain.tsx3 matches

@yassinreg•Updated 3 days ago
125 if (request.method === "POST") {
126 try {
127 const { OpenAI } = await import("https://esm.town/v/std/openai");
128 const openai = new OpenAI();
129
130 const formData = await request.formData();
138 const cvText = new TextDecoder().decode(cvBuffer);
139
140 const completion = await openai.chat.completions.create({
141 messages: [
142 {

speechmain.tsx5 matches

@salon•Updated 3 days ago
197 const [isInitialized, setIsInitialized] = useState(false);
198
199 // --- OpenAI Interaction (Unchanged) ---
200 // !!! IMPORTANT SECURITY WARNING & Val Town Note !!!
201 // ... (same as before)
205 if (!text) return;
206 setStatus("Sending to AI...");
207 console.log("Sending to OpenAI:", text);
208 setAiResponse(""); // Clear previous response
209 setError(null);
213 try {
214 // ---- START: Replace this block in Val Town ----
215 const response = await fetch("https://api.openai.com/v1/chat/completions", {
216 method: "POST",
217 headers: {
226 const errorData = await response.json().catch(() => ({})); // Try to get JSON error details
227 throw new Error(
228 `OpenAI API Error: ${response.status} ${response.statusText} - ${
229 errorData?.error?.message ?? "Check API key or usage limits."
230 }`,
240 speakText(reply);
241 } catch (err: any) {
242 console.error("OpenAI call failed:", err);
243 const errMsg = `AI Error: ${err.message}`;
244 setError(errMsg);

FixItWandgenerate.ts6 matches

@wolf•Updated 3 days ago
1import OpenAI from "https://esm.sh/openai@4.96.0";
2import { search } from "./locations/mod.ts";
3
4const openai = new OpenAI();
5
6/**
39 const audioFile = new File([audioBlob], "a.mp3", { type: "audio/mp3" });
40
41 transcription = await openai.audio.transcriptions.create({
42 file: audioFile,
43 model: "whisper-1",
50 if (transcription) {
51 // Detect possible location references in the transcription
52 const locationDetectionResponse = await openai.chat.completions.create({
53 model: "gpt-4o-mini",
54 messages: [
149 });
150
151 const chatResponse = await openai.chat.completions.create({
152 model: "gpt-4o",
153 messages: messages as any, // Type assertion to fix any TypeScript issues
166`;
167
168 const subjectResponse = await openai.chat.completions.create({
169 model: "gpt-4o-mini",
170 messages: [

OpenTownie_jacksonsystem_prompt.txt4 matches

@stevekrouse•Updated 4 days ago
88Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.
89
90### OpenAI
91
92```ts
93import { OpenAI } from "https://esm.town/v/std/openai";
94const openai = new OpenAI();
95const completion = await openai.chat.completions.create({
96 messages: [
97 { role: "user", content: "Say hello in a creative way" },

guidemain.tsx17 matches

@salon•Updated 4 days ago
1// Val Town Script: Dynamic Character Race Carousel with OpenAI + Plane Tilt + Fanning Cards + Animated Borders
2
3// =============================================================================
5// =============================================================================
6
7// Import OpenAI library from Val Town's standard modules
8import { OpenAI } from "https://esm.town/v/std/openai"; // Ensure 'openai' secret is set
9
10// --- Configuration ---
21 borderAnimationHint?: string; // <<< NEW: Optional hint for border style
22}
23interface OpenAIResponse {
24 races: RaceInfo[];
25}
65];
66
67// --- OpenAI Generation Function ---
68async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> {
69 const openai = new OpenAI();
70 const numToRequest = Math.max(1, NUM_CARDS_TO_GENERATE);
71 const prompt = `
81
82 try {
83 console.info(`Requesting ${numToRequest} race data generation from OpenAI...`);
84 const completion = await openai.chat.completions.create({
85 model: "gpt-4o", // Or your preferred model
86 messages: [{ role: "user", content: prompt }],
90
91 const rawContent = completion.choices[0]?.message?.content;
92 if (!rawContent) throw new Error("OpenAI returned an empty response message.");
93 console.info("Received response from OpenAI. Parsing and validating JSON...");
94 const parsedJson = JSON.parse(rawContent);
95
109 )
110 ) {
111 console.warn(`OpenAI response JSON failed validation for ${numToRequest} races:`, parsedJson);
112 throw new Error("OpenAI response JSON structure, count, data types, or hint value invalid.");
113 }
114
115 const generatedData = (parsedJson as OpenAIResponse).races.map(race => ({
116 ...race,
117 // Ensure borderAnimationHint defaults to 'none' if missing from response
119 }));
120
121 console.info(`Successfully generated and validated ${generatedData.length} races from OpenAI.`);
122 return generatedData;
123 } catch (error) {
124 console.error("Error fetching or processing data from OpenAI:", error);
125 console.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> {
136 const activeRaceData = await generateRaceDataWithOpenAI();
137
138 // Define CSS Styles

policy2main.tsx13 matches

@salon•Updated 4 days ago
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) ---
918 const { OpenAI } = await import("https://esm.town/v/std/openai");
919 const { z } = await import("npm:zod");
920 const { fetch } = await import("https://esm.town/v/std/fetch");
944 }
945
946 // --- Helper Function: Call OpenAI API (Unchanged) ---
947 async function callOpenAI(
948 openai: OpenAI,
949 systemPrompt: string,
950 userMessage: string,
953 ): Promise<{ role: "assistant" | "system"; content: string | object }> {
954 try {
955 const response = await openai.chat.completions.create({
956 model,
957 messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }],
971 else { return { role: "assistant", content }; }
972 } catch (error) {
973 console.error(`OpenAI call failed (ExpectJSON: ${expectJson}):`, error);
974 let msg = "Error communicating with AI.";
975 if (error.message) msg += ` Details: ${error.message}`;
976 if (error.status === 401) msg = "OpenAI Auth Error.";
977 if (error.status === 429) msg = "OpenAI Rate Limit Exceeded.";
978 return { role: "system", content: msg };
979 }
1042 log: LogEntry[],
1043 ): Promise<LogEntry[]> {
1044 const openai = new OpenAI();
1045 log.push({ agent: "System", type: "step", message: "Workflow started." });
1046 log.push({
1115 // --- Content Analysis (Unchanged) ---
1116 log.push({ agent: "System", type: "step", message: "Analyzing content..." });
1117 const anaRes = await callOpenAI(openai, contentAnalysisSystemPrompt, truncText, "gpt-4o", true);
1118 if (anaRes.role === "assistant" && anaRes.content && (anaRes.content as AnalysisResult).summary) { // Type assertion for check
1119 log.push({ agent: "Content Analysis Agent", type: "result", message: anaRes.content });
1124 // --- NEW: Paradigmatic Analysis ---
1125 log.push({ agent: "System", type: "step", message: "Analyzing document context/paradigm..." });
1126 const paradigmRes = await callOpenAI(openai, paradigmaticAnalysisSystemPrompt, truncText, "gpt-4o", true);
1127 if (
1128 paradigmRes.role === "assistant" && paradigmRes.content && (paradigmRes.content as ParadigmaticInfo).documentType
1135 // --- MODIFIED: Reference Extraction ---
1136 log.push({ agent: "System", type: "step", message: "Extracting references..." });
1137 const refRes = await callOpenAI(openai, referenceExtractionSystemPrompt, truncText, "gpt-4o", true); // Use updated prompt
1138 let extRef: Reference[] = []; // Use Reference type
1139 // Check the correct key 'references' from the prompt

Pathwaymain.tsx15 matches

@Get•Updated 4 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 4 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 4 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 4 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.

testOpenAI1 file match

@stevekrouse•Updated 47 mins ago

testOpenAI1 file match

@shouser•Updated 2 days 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": "*",