Glancer3Remix.cursorrules4 matches
94Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.
9596### OpenAI
9798```ts
99import { OpenAI } from "https://esm.town/v/std/openai";
100const openai = new OpenAI();
101const completion = await openai.chat.completions.create({
102messages: [
103{ role: "user", content: "Say hello in a creative way" },
regexToBrainrotmain.tsx4 matches
300{ getRandomRegexExplanation, saveRegexExplanation, getRegexExplanationById },
301ReactMarkdown,
302{ OpenAI },
303{ renderToString },
304{ jsx, jsxs, Fragment },
306import("https://esm.town/v/stainless_em/brainrotdb"),
307import("npm:react-markdown@7"),
308import("https://esm.town/v/std/openai"),
309import("npm:react-dom@19/server.browser"),
310import("npm:react@19/jsx-runtime"),
336}
337338const openai = new OpenAI();
339340const abortController = new AbortController();
341const completion = await openai.chat.completions.create({
342messages: [
343{
untitled-7610main.tsx25 matches
6* Users input their birth details, a sign to focus on, and a life domain.
7* The backend then uses the "Astrologer Prompt" (a detailed system prompt)
8* to query an OpenAI model, which generates a comprehensive astrological report.
9*
10* Core Logic:
13* 2. Backend (Deno Val Function):
14* - Receives these inputs.
15* - Constructs a user message for the OpenAI API. This message includes
16* the raw birth details, focus sign, domain, etc.
17* - Uses the **ENTIRE** "Astrologer Prompt" (with {{sign}} and {{domain}}
18* placeholders filled) as the system prompt for an OpenAI API call.
19* - Calls a powerful OpenAI model (e.g., gpt-4o).
20* - Receives the structured JSON astrological report from OpenAI.
21* - Sends this report back to the client for display.
22*
30* May 28, 2025. The LLM primed by it is assumed to have access to or
31* knowledge of transit data for this date.
32* - OpenAI API Key: An `OPENAI_API_KEY` environment variable must be available
33* in the Val Town environment for `std/openai` to work.
34*
35* Inspired by the structure of the "Goal-Oriented Multi-Agent Stock Analysis Val".
3940// --- Imports ---
41import { OpenAI } from "https://esm.town/v/std/openai";
42// NOTE: Deno.env is used directly for environment variables.
4355}
5657// --- THE ASTROLOGER PROMPT (System Prompt for OpenAI) ---
58// This will be used by the backend to instruct the AI.
59// Placeholders {{sign}} and {{domain}} will be replaced dynamically.
411}
412413// --- Helper Function: Call OpenAI API (Adapted - Robust error handling retained) ---
414async function callOpenAI(
415systemPrompt: string,
416userMessage: string,
422// Simple hash for prompt might not be as useful if {{placeholders}} change content significantly.
423// Consider logging snippet of system prompt if needed for debugging.
424const logPrefix = `OpenAI Call [${callId}] (${model}, JSON: ${isJsonOutputRequired})`;
425log(
426`[INFO] ${logPrefix}: Initiating... System prompt (template used). User message snippet: ${
430431try {
432const openai = new OpenAI(); // API Key from environment
433const response = await openai.chat.completions.create({
434model: model,
435messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }],
439const content = response.choices?.[0]?.message?.content;
440if (!content) {
441log(`[ERROR] ${logPrefix}: OpenAI API returned unexpected or empty response structure.`);
442throw new Error("Received invalid or empty response content from AI model.");
443}
444log(`[SUCCESS] ${logPrefix}: OpenAI call successful.`);
445return { role: "assistant", content: content };
446} catch (error) {
452453if (errorResponseData?.message) {
454errorMessage = `OpenAI Error (${statusCode || "unknown status"}): ${errorResponseData.message}`;
455} else if (errorResponseData?.error?.message) {
456errorMessage = `OpenAI Error (${statusCode || "unknown status"}): ${errorResponseData.error.message}`;
457}
458// ... (retain other specific error message constructions from original Val)
486.replace(new RegExp("{{domain}}", "g"), inputs.focusDomain);
487488// 2. Construct the User Message for the OpenAI API call
489// The Astrologer Prompt expects `birth_chart_data`. We will pass raw birth details
490// and let the LLM (primed with Astrologer Prompt) handle interpretation.
509);
510511// 3. Call OpenAI
512log("[STEP] Calling OpenAI with Astrologer Prompt...");
513// Using gpt-4o as it's capable and the astrological prompt is complex.
514// The ASTROLOGER_SYSTEM_PROMPT_TEMPLATE implies the model should generate JSON.
515const aiResponse = await callOpenAI(populatedSystemPrompt, userMessageJson, "gpt-4o", true, log);
516517// 4. Parse and Return Result
522// (e.g., if the AI itself couldn't perform the analysis and returned an error structure as per its instructions)
523// The ASTROLOGER_SYSTEM_PROMPT_TEMPLATE does not explicitly define an error structure from the AI side,
524// but callOpenAI returns its own {"error": "..."} if the call itself failed.
525if (parsedAiResponse.error && aiResponse.role === "system") { // Error from callOpenAI wrapper
526log(`[ERROR] OpenAI call wrapper reported an error: ${parsedAiResponse.error}`);
527return { error: "Failed to get report from Astrologer AI.", details: parsedAiResponse.error };
528}
personalShopper.cursorrules4 matches
100Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.
101102### OpenAI
103```ts
104import { OpenAI } from "https://esm.town/v/std/openai";
105const openai = new OpenAI();
106const completion = await openai.chat.completions.create({
107messages: [
108{ role: "user", content: "Say hello in a creative way" },
1import { OpenAI } from "https://esm.town/v/std/openai";
2import type { LLMRequest, LLMResponse, SystemDesignRequest, SOARESystem, SystemComponent } from "../../../shared/types/core.ts";
34export class SOAREBrain {
5private openai: OpenAI;
6
7constructor() {
8this.openai = new OpenAI();
9}
1011async reason(request: LLMRequest): Promise<LLMResponse> {
12try {
13const completion = await this.openai.chat.completions.create({
14model: "gpt-4o",
15messages: [
sexy606aianalyzer.ts3 matches
1import { OpenAI } from "https://esm.town/v/std/openai";
2import * as cheerio from "https://esm.sh/cheerio@1.0.0-rc.12";
3import { EarningOpportunity, WebPageContent, AnalysisResult } from "../shared/types.ts";
45const openai = new OpenAI();
67export async function analyzeWebPage(url: string, focus?: string): Promise<AnalysisResult> {
247248try {
249const completion = await openai.chat.completions.create({
250model: "gpt-4o-mini",
251messages: [
7* Uses 'npm:pdf.js-extract' for PDF extraction.
8* Serves HTML UI & API endpoint from the same Val.
9* Assumes 'openai' secret is set in Val Town environment variables.
10*
11* Last Updated: {{current_date}} (Templated Version)
18* max_pdf_size_mb: {{max_pdf_size_mb}}, // e.g., 10
19* text_truncation_length: {{text_truncation_length}}, // e.g., 25000
20* openai_model_name: "{{openai_model_name}}", // e.g., "gpt-4o"
21* contact_form_placeholders_en: { name: "Your Name", email: "Your Email", message: "Message" },
22* contact_form_placeholders_es: { name: "Tu Nombre", email: "Tu Correo", message: "Mensaje" },
639export default async function(req: Request) {
640// --- Dynamic Imports (Unchanged) ---
641const { OpenAI } = await import("https://esm.town/v/std/openai");
642// const { z } = await import("npm:zod"); // Zod might be optional if config is trusted
643const { fetch } = await import("https://esm.town/v/std/fetch");
645646// --- CONFIGURATION (These would be replaced by the template variables at generation time) ---
647const APP_CONFIG = `\{{\app_config_json}}`; // e.g., { openai_model_name: "gpt-4o", text_truncation_length: 25000, ... }
648const ANALYSIS_AGENTS = `\{\{analysis_agents_json}}`; // Array of agent objects
649651async function extractPdfTextNative(data: ArrayBuffer, fileName: string, log: LogEntry[]): Promise<string | null> { /* ... original ... */ }
652653// --- Helper Function: Call OpenAI API (Uses APP_CONFIG for model) ---
654async function callOpenAI(
655openai: OpenAI,
656systemPrompt: string,
657userMessage: string,
658modelFromConfig = APP_CONFIG.openai_model_name || "gpt-4o", // Use configured model
659expectJson = false,
660): Promise<{ role: "assistant" | "system"; content: string | object }> {
661/* ... original logic, but use modelFromConfig ... */
662const model = modelFromConfig;
663// ... rest of the original callOpenAI function
664try {
665const response = await openai.chat.completions.create({
666model,
667messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }],
701log: LogEntry[],
702): Promise<LogEntry[]> {
703const openai = new OpenAI();
704log.push({ agent: "System", type: "step", message: "Workflow started." });
705// ... initial logging of input type ...
730// If chaining is needed, {{previous_output}} could be another placeholder in prompts.
731732const agentResult = await callOpenAI(
733openai,
734agentSystemPrompt, // The agent's specific prompt
735truncText, // User message is the doc text itself, or could be empty if prompt is self-contained
736APP_CONFIG.openai_model_name,
737agentConfig.expects_json
738);
830* 1. Define Application Configuration:
831* Fill in the \`{{app_config_json}}\` placeholder with general settings for your app
832* (e.g., OpenAI model, max file size, default language).
833*
834* 2. Define Analysis Agents:
836* - `agent_id`: A unique machine-readable ID.
837* - `agent_name_en`/`agent_name_es`: Human-readable names for UI and logs.
838* - `system_prompt`: The OpenAI prompt for this agent. Can use `{{document_text}}`.
839* - `expects_json`: Boolean, if the prompt asks OpenAI for JSON output.
840* - `ui_display_info`: How to render this agent's results:
841* - `card_title_en`/`card_title_es`: Title for the results card.
857* and `{{app_config.document_format_accepted_label}}` (e.g. "PDF") for UI text.
858*
859* 5. OpenAI API Key:
860* Ensure your environment (e.g., Val Town secrets) has the `OPENAI_API_KEY` (or the appropriate
861* environment variable name for the `OpenAI` library) set.
862*
863* 6. Deployment:
74### Tech Stack
75- **Backend**: Hono.js for API routing
76- **AI**: OpenAI GPT-4o-mini for content analysis
77- **Web Scraping**: Cheerio for HTML parsing
78- **Frontend**: Vanilla JavaScript with TailwindCSS
91## 🔧 Environment Setup
9293The analyzer uses OpenAI's API which is automatically configured in Val Town. No additional setup required!
9495## 📊 What It Analyzes
1import { Hono } from "https://esm.sh/hono@3.11.7";
2import { OpenAI } from "https://esm.town/v/std/openai";
3import { readFile } from "https://esm.town/v/std/utils/index.ts";
4import { analyzeWebPage } from "./analyzer.ts";
111}
112
113if (error.message.includes("OpenAI") || error.message.includes("API key")) {
114return c.json({ error: "AI analysis service requires API key configuration. Please contact the administrator." }, 503);
115}
4// SERVER-SIDE LOGIC (TypeScript)
5// =============================================================================
6import { OpenAI } from "https://esm.town/v/std/openai";
78// --- Configuration ---
23maskSrc?: string;
24}
25interface OpenAIResponse {
26races: RaceInfo[];
27}
105];
106107// --- OpenAI Generation Function ---
108async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> {
109const openai = new OpenAI();
110const numToRequest = Math.max(1, NUM_CARDS_TO_GENERATE);
111const prompt =
126Return STRICTLY as a single JSON object: { "races": [ { race1 }, { race2 }, ... ] }. No introductory text or explanations outside the JSON structure.`;
127try {
128console.info(`Requesting ${numToRequest} race data generation from OpenAI...`);
129const completion = await openai.chat.completions.create({
130model: "gpt-4o",
131messages: [{ role: "user", content: prompt }],
134});
135const rawContent = completion.choices[0]?.message?.content;
136if (!rawContent) throw new Error("OpenAI returned an empty response message.");
137138let parsedJson;
140parsedJson = JSON.parse(rawContent);
141} catch (parseError) {
142console.error("Failed to parse OpenAI JSON response:", parseError);
143console.error("Raw OpenAI response:", rawContent);
144throw new Error(`JSON Parsing Error: ${parseError.message}`);
145}
160) {
161console.warn(
162`OpenAI response JSON failed validation for ${numToRequest} races:`,
163JSON.stringify(parsedJson, null, 2),
164);
165throw new Error(
166"OpenAI response JSON structure, count, data types, color format, hint value, or mask URL invalid.",
167);
168}
169170const generatedData = (parsedJson as OpenAIResponse).races.map(race => ({
171...race,
172borderAnimationHint: race.borderAnimationHint || "none",
173}));
174console.info(`Successfully generated and validated ${generatedData.length} races from OpenAI.`);
175return generatedData;
176} catch (error) {
177console.error("Error fetching or processing data from OpenAI:", error);
178console.warn("Using fallback race data due to the error.");
179return fallbackRaceData.slice(0, numToRequest).map(race => ({
186// --- Main HTTP Handler (Val Town Entry Point) ---
187export default async function server(request: Request): Promise<Response> {
188const activeRaceData = await generateRaceDataWithOpenAI();
189190const css = `