Search
Code3,247
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" },
```## 7. Get OpenAI API Key1. Go to [OpenAI's website](https://platform.openai.com/)2. Sign up or log in3. Navigate to the API keys section6. Add it to your `.env` file: ``` OPENAI_API_KEY=your_openai_api_key_here ```
* Uses 'npm:pdf.js-extract' for direct PDF text extraction. * Serves HTML UI & API endpoint from 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 (Dashboard UI, Localization, Animation 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: 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}`; } // Check for specific error types if needed (e.g., rate limits, auth) if (error.status === 401) errorMessage = "Authentication error with OpenAI API. Check your secret key."; if (error.status === 429) errorMessage = "OpenAI API rate limit exceeded. Please try again later."; return { role: "system", content: errorMessage }; log: LogEntry[], ): Promise<LogEntry[]> { // Returns the completed log array const openai = new OpenAI(); // Assumes API key is in environment variables log.push({ agent: "System", type: "step", message: "Starting analysis workflow." }); // --- 2. Content Analysis --- log.push({ agent: "System", type: "step", message: "Starting Content Analysis..." }); const analysisResponse = await callOpenAI(openai, contentAnalysisSystemPrompt, truncatedText, "gpt-4o", true); // Use gpt-4o let analysisResult: AnalysisResult | null = null; if (analysisResponse.role === "assistant" && typeof analysisResponse.content === "object") { // --- 3. Citation Extraction --- log.push({ agent: "System", type: "step", message: "Starting Citation Extraction..." }); const citationResponse = await callOpenAI(openai, citationExtractionSystemPrompt, truncatedText, "gpt-4o", true); // Use gpt-4o let extractedCitations: Citation[] = []; if ( message: \`AI response was not the expected JSON format. Received: \${JSON.stringify(citationResponse.content).substring(0, 200)}...\`, }); } else { // System error from callOpenAI log.push({ agent: "Citation Extraction Agent", type: "error", message: citationResponse.content }); }
if (request.method === 'POST') { try { const { OpenAI } = await import("https://esm.town/v/std/openai"); const openai = new OpenAI(); const formData = await request.formData(); const cvText = new TextDecoder().decode(cvBuffer); const completion = await openai.chat.completions.create({ messages: [ {
if (request.method === "POST") { try { const { OpenAI } = await import("https://esm.town/v/std/openai"); const openai = new OpenAI(); const formData = await request.formData(); const cvText = new TextDecoder().decode(cvBuffer); const completion = await openai.chat.completions.create({ messages: [ {
if (request.method === "POST") { try { const { OpenAI } = await import("https://esm.town/v/std/openai"); const openai = new OpenAI(); const formData = await request.formData(); const cvText = new TextDecoder().decode(cvBuffer); const completion = await openai.chat.completions.create({ messages: [ {
const [isInitialized, setIsInitialized] = useState(false); // --- OpenAI Interaction (Unchanged) --- // !!! IMPORTANT SECURITY WARNING & Val Town Note !!! // ... (same as before) if (!text) return; setStatus("Sending to AI..."); console.log("Sending to OpenAI:", text); setAiResponse(""); // Clear previous response setError(null); try { // ---- START: Replace this block in Val Town ---- const response = await fetch("https://api.openai.com/v1/chat/completions", { method: "POST", headers: { const errorData = await response.json().catch(() => ({})); // Try to get JSON error details throw new Error( `OpenAI API Error: ${response.status} ${response.statusText} - ${ errorData?.error?.message ?? "Check API key or usage limits." }`, speakText(reply); } catch (err: any) { console.error("OpenAI call failed:", err); const errMsg = `AI Error: ${err.message}`; setError(errMsg);
import OpenAI from "https://esm.sh/openai@4.96.0";import { search } from "./locations/mod.ts";const openai = new OpenAI();/** const audioFile = new File([audioBlob], "a.mp3", { type: "audio/mp3" }); transcription = await openai.audio.transcriptions.create({ file: audioFile, model: "whisper-1", if (transcription) { // Detect possible location references in the transcription const locationDetectionResponse = await openai.chat.completions.create({ model: "gpt-4o-mini", messages: [ }); const chatResponse = await openai.chat.completions.create({ model: "gpt-4o", messages: messages as any, // Type assertion to fix any TypeScript issues`; const subjectResponse = await openai.chat.completions.create({ model: "gpt-4o-mini", messages: [
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" },
// Val Town Script: Dynamic Character Race Carousel with OpenAI + Plane Tilt + Fanning Cards + Animated Borders// =============================================================================// =============================================================================// Import OpenAI library from Val Town's standard modulesimport { OpenAI } from "https://esm.town/v/std/openai"; // Ensure 'openai' secret is set// --- Configuration --- borderAnimationHint?: string; // <<< NEW: Optional hint for border style}interface OpenAIResponse { races: RaceInfo[];}];// --- OpenAI Generation Function ---async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> { const openai = new OpenAI(); const numToRequest = Math.max(1, NUM_CARDS_TO_GENERATE); const prompt = ` try { console.info(`Requesting ${numToRequest} race data generation from OpenAI...`); const completion = await openai.chat.completions.create({ model: "gpt-4o", // Or your preferred 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.info("Received response from OpenAI. Parsing and validating JSON..."); const parsedJson = JSON.parse(rawContent); ) ) { console.warn(`OpenAI response JSON failed validation for ${numToRequest} races:`, parsedJson); throw new Error("OpenAI response JSON structure, count, data types, or hint value invalid."); } const generatedData = (parsedJson as OpenAIResponse).races.map(race => ({ ...race, // Ensure borderAnimationHint defaults to 'none' if missing from response })); 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."); // Ensure fallback data also has the hint, slice correctly// --- Main HTTP Handler (Val Town Entry Point) ---export default async function server(request: Request): Promise<Response> { const activeRaceData = await generateRaceDataWithOpenAI(); // Define CSS Styles
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