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=8&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"(1032ms)

guidemain.tsx29 matches

@Get•Updated 4 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 4 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 4 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 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" },

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: [

flashcardsmain.tsx4 matches

@omar1•Updated 4 days ago
89export default async function server(request: Request): Promise<Response> {
90 if (request.method === "POST" && new URL(request.url).pathname === "/generate") {
91 const { OpenAI } = await import("https://esm.town/v/std/openai");
92 const openai = new OpenAI();
93
94 try {
95 const { topic } = await request.json();
96
97 const completion = await openai.chat.completions.create({
98 model: "gpt-4o-mini",
99 messages: [
137
138 const flashcardsResponse = completion.choices[0].message.content;
139 console.log("Raw OpenAI response:", flashcardsResponse); // Detailed debug logging
140
141 // More robust JSON parsing with extensive error handling

stevensDemo.cursorrules4 matches

@mudassar864•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" },

EEPMOnitoringmain.tsx4 matches

@solomonferede•Updated 5 days ago
2import { createRoot } from "https://esm.sh/react-dom@18.2.0/client";
3import React, { useEffect, useState } from "https://esm.sh/react@18.2.0";
4import { OpenAI } from "https://esm.town/v/std/openai";
5import { sqlite } from "https://esm.town/v/stevekrouse/sqlite";
6
113export default async function server(request: Request): Promise<Response> {
114 if (request.method === "POST") {
115 const openai = new OpenAI();
116 const KEY = "EEPMOnitoring";
117
157 if (existingArticle.rows.length === 0) {
158 try {
159 const analysis = await openai.chat.completions.create({
160 model: "gpt-4o-mini",
161 messages: [
188 });
189 } catch (aiError) {
190 console.error("OpenAI analysis error:", aiError);
191 // Fallback analysis
192 await sqlite.execute(

finalRoundFeedmain.tsx3 matches

@gabrieledarrigo•Updated 5 days ago
1import { Bot } from "https://esm.sh/grammy@1.25.0";
2import { OpenAI } from "https://esm.town/v/std/openai";
3import { XMLParser } from "npm:fast-xml-parser";
4
35}
36
37const openai = new OpenAI();
38const bot = new Bot(TELEGRAM_TOKEN);
39
49
50async function summarizeDescription(item: RSSItem): Promise<string> {
51 const completion = await openai.chat.completions.create({
52 messages: [
53 {

testOpenAI1 file match

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