Search
Code3,282
// @ts-ignoreimport { OpenAI } from "https://esm.town/v/std/openai?v=4";import { sqlite } from "https://esm.town/v/std/sqlite?v=4"; } const openai = new OpenAI(); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [
// @ts-ignoreimport { OpenAI } from "https://esm.town/v/std/openai?v=4";import { Hono } from "npm:hono@4.4.12"; if (!userText) throw new Error("User description is required."); const openai = new OpenAI(); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [ } const openai = new OpenAI(); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [ } const openai = new OpenAI(); const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [
export class ApiLogger { /** * Log OpenAI API response with headers and request ID */ static logOpenAIResponse(response: Response, data: Record<string, unknown>, context: string): void { const respId = response.headers.get("x-request-id") || response.headers.get("resp-id") || "unknown"; const model = data.model || "unknown"; console.log(`OpenAI ${context}: model=${model} resp_id=${respId} status=${response.status}`); console.log("Response headers:", Object.fromEntries(response.headers.entries())); console.log("Response data:", JSON.stringify(data, null, 2));
import { OpenAI } from "https://esm.town/v/std/openai?v=4";import ValTown from "npm:@valtown/sdk@1.5.0";import { Hono } from "npm:hono@4.4.12";Adhere to these non-negotiable rules:1. **Analyze and Elevate:** Scrutinize the user's core idea. Augment it with essential, modern features. For a "link shortener," this means adding analytics like click counts.2. **MANDATE NOVEL AI INTEGRATION:** Every application MUST have a valuable, non-trivial OpenAI feature at its core. Invent a creative integration that provides unique value. - *Example for a Todo List:* An AI feature that suggests the most logical next task based on the current list's context. - *Example for a Blog:* An AI-powered assistant to generate 5 compelling title variations for a given article body.3. **Mandate Interactive UI with Inputs:** The application's primary purpose must be interactive. The UI MUST feature a form with input fields (\`<input>\`, \`<textarea>\`) and a submission button (\`<button>\`) to allow users to create, modify, or submit data. A purely read-only interface is not acceptable.4. **Enforce Strict JSON Contract for AI:** When defining the \`openai_integration\`, the \`prompt_template\` MUST explicitly instruct the AI to respond in JSON format. The \`expected_output\` MUST then provide a stringified JSON example of this exact structure, which will serve as a contract for the developer AI.5. **Mandate Val Town Standard Library & Schema Structure:** Explicitly command the use of Val Town's standard library. For structured data, mandate \`std/sqlite\`. The database schema MUST be defined as an array of strings, where each string is a single, complete 'CREATE TABLE' statement.6. **Define a Polished UI/UX Vision:** Describe a modern, aesthetically pleasing user interface, specifying typography from Google Fonts, a CSS variable-based color palette, and a responsive layout using Flexbox or Grid. The UI description must detail the form and input elements required by Rule #3. "application_type": "The type of application (e.g., 'AI-Powered Poll Creator', 'Smart Guestbook')", "core_features": ["An array of specific, actionable features, including the user's ability to submit data."], "openai_integration": { "feature_description": "A clear description of the AI feature.", "prompt_template": "A concise, effective prompt for the LLM that explicitly tells it to respond in JSON format.",- **User's Simple Idea:** "A poll app"- **Your Enriched JSON Output:** {"application_type":"AI-Enhanced Poll Application","core_features":["Users can create a poll with a question and multiple options using a form.","A unique URL is generated for each poll.","Visitors can vote on options.","Results are displayed in real-time with percentages."],"openai_integration":{"feature_description":"When creating a poll, an AI suggests additional, diverse poll options based on the user's question to encourage more engaging polls.","prompt_template":"Given the poll question '{question}' and existing options {options}, generate a JSON object with a key 'suggestions' containing an array of 3 distinct, complementary poll options.","expected_output":"{\\"suggestions\\": [\\"Option A\\", \\"Option B\\", \\"Option C\\"]}"},"data_model":{"tool":"std/sqlite","schema":["CREATE TABLE polls (id TEXT PRIMARY KEY, question TEXT NOT NULL);","CREATE TABLE options (id INTEGER PRIMARY KEY AUTOINCREMENT, poll_id TEXT NOT NULL, text TEXT NOT NULL, votes INTEGER DEFAULT 0, FOREIGN KEY (poll_id) REFERENCES polls(id));"]},"ui_ux_guidelines":{"font_family":"'Inter', sans-serif","google_font_url":"https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700&display=swap","css_variables":{"--bg-color":"#f0f2f5","--card-bg":"#ffffff","--text-primary":"#1a202c","--text-secondary":"#4a5568","--primary-color":"#4263eb","--border-color":"#e2e8f0"},"layout_notes":"A clean, centered UI. The main feature is a card-based form for creating a poll, with inputs for the question and options. Results should be displayed using a bar-graph style within each option."}}`;--- CORE PRINCIPLES ---1. **Deno-First:** All code is for the Deno runtime, using modern JavaScript/TypeScript.2. **Version Pin ALL Imports:** Always use version-pinned imports (e.g., \`npm:hono@4.4.12\`, \`https://esm.town/v/std/openai?v=4\`) to guarantee stability.3. **OpenAI is Core:** The specified OpenAI feature must be a central, value-adding part of the application.4. **Use Standard Library:** Religiously use the Val Town standard library (\`std/sqlite\`, \`std/blob\`) as directed by the JSON specification.5. **Secrets in Environment:** API keys or other secrets must be accessed via \`Deno.env.get()\`. Never hard-code them.* **Query:** \`const { rows } = await sqlite.execute("SELECT * FROM users");\`**OpenAI JSON Usage (MANDATORY PATTERN):**\`\`\`typescriptimport { OpenAI } from "https://esm.town/v/std/openai?v=4";const openai = new OpenAI();const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "user", content: "Tell me a joke about APIs in a JSON object with a 'joke' key." }], * In this context, template literals (strings with backticks \`\`) MUST be standard and valid TypeScript. * **NEVER escape backticks or dollar-sign placeholders in this context.** * **CRITICAL MISTAKE TO AVOID:** Writing \`const x = \\\`hello \\\${world}\\\`;\` in server code is a FATAL ERROR that will crash the application. It must be \`const x = \`hello \${world}\`;\`. This applies especially to OpenAI prompt messages.2. **CLIENT-SIDE CONTEXT (The JS inside the \`<script>\` tag within the HTML string):**import { Hono } from "npm:hono@4.4.12";import { sqlite } from "https://esm.town/v/std/sqlite?v=4";import { OpenAI } from "https://esm.town/v/std/openai?v=4";const DB_SCHEMA = [ if (!message) return c.json({ error: "Message is required." }, 400); const openai = new OpenAI(); // This is a server-side OpenAI call. Per escaping rules, template literals here are standard and unescaped. const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: [ } const openai = new OpenAI(); // STEP 1: Enrich the user's idea into a detailed JSON prompt const enrichmentCompletion = await openai.chat.completions.create({ model: "gpt-4o", messages: [ const codeGenUserMessage = `Generate the Val Town code for the following specification: ${enrichedPromptJson}`; // STEP 2: Generate code with OpenAI using the enriched JSON prompt const codeGenCompletion = await openai.chat.completions.create({ model: "gpt-4o", messages: [ // --- POST-PROCESSING STEPS --- let correctedCode = generatedCode // Fix incorrectly escaped server-side OpenAI prompt template literals .replace(/(content:\s*)\\\`/g, "$1`") .replace(/\\\$\{/g, "${")
// @ts-ignoreimport { blob } from "https://esm.town/v/std/blob?v=11";import { OpenAI } from "https://esm.town/v/std/openai";import { sqlite } from "https://esm.town/v/std/sqlite?v=4";import { Hono } from "npm:hono@4.4.12";// --- CORE AI & DATABASE LOGIC ---const openai = new OpenAI();async function getTodos() {async function addTodo(rawTitle: string) { // Step 1: Refine the incoming task. const refinementCompletion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "system", content: TASK_REFINEMENT_PROMPT }, { const existingTodosForCheck = existingTodosRaw.map(r => ({ id: r[0], title: r[1] })); const duplicateCheckCompletion = await openai.chat.completions.create({ model: "gpt-4o", messages: [
// @ts-ignoreimport { OpenAI } from "https://esm.town/v/std/openai?v=4";// --- AI BEHAVIORAL GUIDELINES & PROMPTS --- const url = new URL(req.url); const action = url.searchParams.get("action"); const openai = new OpenAI(); if (req.method !== "POST") { Desired Resolution: ${userInput.resolution} `; const analysisCompletion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "system", content: PROMPT_ANALYZE }, { role: "user", content: userContext }], sender: userInput.sender, }; const composeCompletion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "system", content: PROMPT_COMPOSE }, { // --- Stage 3: Internal Critique of Pre-Draft --- const firstReviewCompletion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "system", content: PROMPT_REDTEAM_REVIEW }, { role: "user", content: preDraftText }], JSON.stringify(firstCritique) }`; const revisionCompletion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "system", content: PROMPT_REVISE }, { role: "user", content: revisionUserMessage }], // --- Stage 5: Final Critique of Revised Draft --- const finalReviewCompletion = await openai.chat.completions.create({ model: "gpt-4o", messages: [{ role: "system", content: PROMPT_REDTEAM_REVIEW }, { role: "user", content: revisedLetterText }],
// @ts-ignoreimport { OpenAI } from "https://esm.town/v/std/openai?v=4";// --- AI SYSTEM PROMPT --- if (req.method === "POST" && action === "generate") { try { const openai = new OpenAI(); const body = await req.json(); const topic = body.topic; ]; const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: messages,
// @ts-ignoreimport { OpenAI } from "https://esm.town/v/std/openai?v=4";// --- AI SYSTEM PROMPTS --- <main class="game-window" id="game-window"> </main> <footer class="footer">Powered by <a href="${sourceUrl}" target="_blank">Val Town</a> & OpenAI</footer></div> if (req.method === "POST") { try { const openai = new OpenAI(); const body = await req.json(); } const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: messages,
### ✅ Phase 2: Data Ingestion & AI Rating (COMPLETE)- NYT data fetching and parsing with category words- OpenAI integration for category rating with full context- Cron job for daily automation- Historical backfill on first run- **Database**: SQLite with versioned table names for schema changes- **AI**: OpenAI GPT-4o-mini for cost-effective rating generation- **Frontend**: React 18.2.0 with TailwindCSS for rapid development- **Backend**: Hono for lightweight, fast API routes
import { OpenAI } from "https://esm.town/v/std/openai";// ================================================================= const url = new URL(req.url); const action = url.searchParams.get("action"); const openai = new OpenAI(); if (req.method === "POST" && action === "getNextAiTurn") { ]; const completion = await openai.chat.completions.create({ model: "gpt-4o", messages: messages,
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