Search

3,342 results found for openai (2015ms)

Code
3,247

Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to cre
### OpenAI
```ts
import { 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 Key
1. Go to [OpenAI's website](https://platform.openai.com/)
2. Sign up or log in
3. Navigate to the API keys section
6. Add it to your `.env` file:
```
OPENAI_API_KEY=your_openai_api_key_here
```
Get/Project/main.tsx
15 matches
* 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: userMessa
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)
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
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
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, truncatedT
let extractedCitations: Citation[] = [];
if (
message: \`AI response was not the expected JSON format. Received: \${JSON.stringify(cit
});
} else { // System error from callOpenAI
log.push({ agent: "Citation Extraction Agent", type: "error", message: citationResponse.
}
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 deta
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 cre
### OpenAI
```ts
import { 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" },
salon/guide/main.tsx
17 matches
// Val Town Script: Dynamic Character Race Carousel with OpenAI + Plane Tilt + Fanning Cards + A
// =============================================================================
// =============================================================================
// Import OpenAI library from Val Town's standard modules
import { 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:`, parsedJs
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
}));
enerated 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