Search

3,307 results found for openai (1839ms)

Code
3,212

Get/json/main.tsx
27 matches
import { createRoot } from "https://esm.sh/react-dom@18.2.0/client";
import React, { useEffect, useRef, useState } from "https://esm.sh/react@18.2.0";
import { OpenAI } from "https://esm.town/v/std/openai";
// ========================================================================
}
const openai = new OpenAI();
// --- Centralized OpenAI Call Function ---
async function callOpenAI(
systemPrompt: string,
userMessage: string,
): Promise<{ role: "assistant" | "system"; content: string } | ReadableStream<Uint8Array>> {
try {
serverLog("INFO", "Calling OpenAI", {
model,
promptStart: systemPrompt.substring(0, 50).replace(/\s+/g, " ") + "...",
});
const response = await openai.chat.completions.create({
model: model,
response_format: expectJson && !isStreaming ? { type: "json_object" } : undefined,
if (isStreaming) {
serverLog("INFO", "OpenAI call initiated (Streaming)");
if (response instanceof ReadableStream) {
return response;
if (done) {
controller.close();
serverLog("INFO", "OpenAI Stream finished.");
} else {
const content = value?.choices?.[0]?.delta?.content || "";
}
} catch (err) {
serverLog("ERROR", "Error reading from OpenAI stream iterator", { error: (err as
controller.error(err);
}
});
} else {
throw new Error("OpenAI response is not a readable stream or async iterator when strea
}
} else {
const content = (response as any).choices?.[0]?.message?.content;
if (!content) {
serverLog("ERROR", "OpenAI API returned empty content (non-streaming)", { response });
throw new Error("Received invalid or empty response from AI model.");
}
try {
JSON.parse(content);
serverLog("INFO", "OpenAI call successful (JSON validated)");
return { role: "assistant", content };
} catch (jsonError) {
serverLog("ERROR", "OpenAI response is not valid JSON", {
contentPreview: content.substring(0, 200) + "...",
error: (jsonError as Error).message,
}
} else {
serverLog("INFO", "OpenAI call successful (Text)");
return { role: "assistant", content };
}
const errorMessageString = error instanceof Error ? error.message : String(error);
const errorStatus = error instanceof Error ? (error as any).status ?? (error as any).respo
serverLog("ERROR", "OpenAI API call failed", {
model,
error: errorMessageString,
const statusCode = errorStatus;
if (statusCode === 401) userFriendlyErrorMessage = "OpenAI Auth Error (401). Check Val Tow
else if (statusCode === 429)
userFriendlyErrorMessage = "OpenAI Rate Limit/Quota Error (429). Check OpenAI plan/usage
else if (statusCode === 400)
userFriendlyErrorMessage = "OpenAI Bad Request (400). Possible issue with request or con
+ errorMessageString;
else if (errorMessageString?.includes("maximum context length"))
userFriendlyErrorMessage = "OpenAI Context Length Error (400). The request is too long."
else if (statusCode >= 500)
userFriendlyErrorMessage = "OpenAI Server Error (" + statusCode
+ "). OpenAI might be having issues. Try again later.";
else if (error instanceof Error && (error as any).code === "ENOTFOUND")
ErrorMessage = "Network Error (ENOTFOUND). Cannot resolve OpenAI API address.";
else if (error instanceof Error && (error as any).code === "ECONNREFUSED")
essage = "Network Error (ECONNREFUSED). Cannot connect to OpenAI API.";
else if (errorMessageString?.includes("secret")) userFriendlyErrorMessage = errorMessageSt
else userFriendlyErrorMessage = userFriendlyErrorMessage + " Details: " + errorMessageStri
}
const response = await callOpenAI(systemPrompt, userMessageContent, "gpt-4o-mini", agent
if (typeof response === "string" || response instanceof ReadableStream) {
if (shouldStream) {
const stream = await callOpenAI(agentAPrompt, lastUserMessageContent, "gpt-4o-mini", tru
if (!(stream instanceof ReadableStream)) throw new Error("Expected ReadableStream for st
});
} else {
const agentAResponse = await callOpenAI(agentAPrompt, lastUserMessageContent, "gpt-4o-mi
if (typeof agentAResponse === "string" || agentAResponse instanceof ReadableStream)
throw new Error("Expected structured response for non-streaming.");
+ "Output ONLY raw JSON.";
const agentBResponse = await callOpenAI(agentBPrompt, toolRequest.query, "gpt-4o-mini", tr
if (typeof agentBResponse === "string" || agentBResponse instanceof ReadableStream)
throw new Error("Expected structured response for tool.");
export default async function server(request: Request): Promise<Response> {
const { OpenAI } = await import("https://esm.town/v/std/openai");
const openai = new OpenAI();
if (request.method === "POST") {
if (url.pathname === "/chat") {
const completion = await openai.chat.completions.create({
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" },
async generate(prompt: string, options: { maxTokens?: number } = {}) {
try {
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${Deno.env.get("OPENAI_API_KEY")}`,
},
body: JSON.stringify({
import { Bot } from "https://deno.land/x/grammy@v1.35.0/mod.ts";
import { DateTime } from "https://esm.sh/luxon@3.4.4";
import OpenAI from "npm:openai@4.5.0";
import { BOT_SENDER_ID, BOT_SENDER_NAME, storeChatMessage } from "../importers/handleTelegramMes
import { formatMemoriesForPrompt, getRelevantMemories } from "../memoryUtils.ts";
async function generateBriefingContent(
openai: OpenAI,
memories: unknown[],
today: DateTime,
`.trim();
const completion = await openai.chat.completions.create({
model: "gpt-4",
messages: [
// 1. Récupérer variables
const telegramToken = Deno.env.get("TELEGRAM_TOKEN");
const openaiKey = Deno.env.get("OPENAI_API_KEY");
if (!telegramToken || !openaiKey) {
console.error("🚨 TELEGRAM_TOKEN et/ou OPENAI_API_KEY manquant·e·s");
return;
}
}
// 2. Initialiser OpenAI et Bot
const openai = new OpenAI({ apiKey: openaiKey });
const bot = new Bot(telegramToken);
// 5. Générer le contenu
console.log("📝 Generating briefing content...");
const content = await generateBriefingContent(openai, memories, today);
console.log("📨 Briefing content received");
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" },
import { nanoid } from "https://esm.sh/nanoid@5.0.5";
import { sqlite } from "https://esm.town/v/stevekrouse/sqlite";
import OpenAI from "npm:openai@4.5.0";
// Nom de la table et tag
}
// Génère les fun facts via OpenAI ChatGPT‑4
async function generateFunFacts(previousFacts: {date: string; text: string}[]) {
const openaiKey = Deno.env.get("OPENAI_API_KEY");
if (!openaiKey) {
console.error("OpenAI API key is not configured.");
return [];
}
const openai = new OpenAI({ apiKey: openaiKey });
// Prépare le contexte des anciens faits
try {
const completion = await openai.chat.completions.create({
model: "gpt-4",
messages: [
return facts;
} catch (e) {
console.error("Error generating fun facts with OpenAI:", e);
return [];
}
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" },
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" },
if (typeof document !== "undefined") { client(); }
export default async function server(request: Request): Promise<Response> {
const { OpenAI } = await import("https://esm.town/v/std/openai");
const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");
const openai = new OpenAI();
// Use the val's URL as a unique key for database tables
const echoPrompt = getEchoPrompt();
const completion = await openai.chat.completions.create({
messages: [
{
// First, generate the agent prompt
const completion2 = await openai.chat.completions.create({
messages: [
{
// Then, generate commands for the agent based on its purpose and description
const commandsCompletion = await openai.chat.completions.create({
messages: [
{
}
// Format the history into OpenAI message format
const messages = [
{
// Add conversation history if it exists
if (history && history.length > 0) {
// Filter out system messages and map to OpenAI format
history.forEach(msg => {
if (msg.role !== "system") {
// Chat with the agent using the stored prompt and history
const completion = await openai.chat.completions.create({
messages: messages,
model: "gpt-4o-mini",
// Execute the command with the AI
const completion = await openai.chat.completions.create({
messages: messages,
model: "gpt-4o-mini",