Search

3,377 results found for openai (4730ms)

Code
3,282

### `ai-explainer.ts`
An AI-powered block explainer that uses OpenAI to generate detailed explanations.
**Requirements:**
- Set `OPENAI_API_KEY` environment variable
- Val Town Pro subscription (for OpenAI API access)
**Test:**
* AI-Powered Block Explainer
*
* This is an example custom block explainer that uses OpenAI to generate
* detailed explanations of code blocks.
*
*/
import { OpenAI } from "https://esm.sh/openai@4.28.0";
export default async function(req: Request) {
const blockCode = lines.slice(blockInfo.start - 1, blockInfo.end).join('\n');
// Initialize OpenAI (requires OPENAI_API_KEY environment variable)
const openai = new OpenAI({
apiKey: Deno.env.get('OPENAI_API_KEY'),
});
\`\`\``;
const completion = await openai.chat.completions.create({
messages: [
{
}
async function callOpenAI(messages: any[], tools: any[]) {
const OPENAI_API_KEY = Deno.env.get("OPENAI_API_KEY");
const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${OPENAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "openai/gpt-4o",
messages,
tools,
];
let completion = await callOpenAI(messages, tools);
let weatherData = null;
let locationData = null;
}
completion = await callOpenAI(messages, tools);
if (!completion.choices[0].message.tool_calls) {
if (body.action === 'chat') {
const { OpenAI } = await import("https://esm.town/v/std/openai");
const openai = new OpenAI();
const completion = await openai.chat.completions.create({
messages: [
{ role: "system", content: body.systemPrompt },
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" },
legal/kay/main.tsx
13 matches
* is defined directly in the main function handler below.
*
* Assumes the 'openai' secret, containing your OpenAI API key, is set in your Val Town environm
*
* Last Updated: 2024-05-22
export default async function(req: Request) {
// --- Dynamic Imports ---
const { OpenAI } = await import("https://esm.town/v/std/openai");
const { fetch } = await import("https://esm.town/v/std/fetch");
const { PDFExtract } = await import("npm:pdf.js-extract");
max_pdf_size_mb: 10,
text_truncation_length: 25000,
openai_model_name: "gpt-4o",
contact_form_placeholders_en: { name: "Your Name", email: "Your Email", message: "Message" }
contact_form_placeholders_es: { name: "Tu Nombre", email: "Tu Correo", message: "Mensaje" },
}
// --- Helper Function: Call OpenAI API ---
async function callOpenAI(
openai: OpenAI,
systemPrompt: string,
userMessage: string,
modelFromConfig = APP_CONFIG.openai_model_name || "gpt-4o",
expectJson = false,
): Promise<{ role: "assistant" | "system"; content: string | object }> {
const model = modelFromConfig;
try {
const response = await openai.chat.completions.create({
model,
messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessa
}
} catch (error) {
console.error("OpenAI API Error:", error.message);
return { role: "system", content: `AI Error: ${error.message}` };
}
log: LogEntry[],
): Promise<LogEntry[]> {
const openai = new OpenAI();
log.push({ agent: "System", type: "step", message: "Workflow started." });
const agentSystemPrompt = agentConfig.system_prompt.replace("{{document_text}}", truncText
const agentResult = await callOpenAI(
openai,
agentSystemPrompt,
truncText,
APP_CONFIG.openai_model_name,
agentConfig.expects_json,
);
import { OpenAI } from "https://esm.town/v/std/openai";
import { sqlite } from "https://esm.town/v/std/sqlite";
import { readFile } from "https://esm.town/v/std/utils/index.ts";
}
// Initialize OpenAI
const openai = new OpenAI();
// Initialize cache on startup with error handling
}
console.log(`Fetching fresh data from OpenAI for: "${plantName}"`);
// If not cached, fetch from OpenAI
const prompt =
`Please provide detailed information about the plant "${plantName}" in the following JSON
Only return the JSON object, no additional text.`;
const completion = await openai.chat.completions.create({
messages: [
{ role: "user", content: prompt },
if (!responseText) {
return c.json({ error: "No response from OpenAI" }, 500);
}
}
// Parse the JSON response from OpenAI
const plantInfo: PlantInfo = JSON.parse(cleanedResponse);
export default async function(req: Request) {
const { OpenAI } = await import("https://esm.town/v/std/openai");
const { PDFExtract } = await import("npm:pdf.js-extract");
const action = url.searchParams.get("action");
const sourceUrl = import.meta.url.replace("esm.town", "val.town");
const openai = new OpenAI();
const MAX_TEXT_SUGGEST = 20000;
const MAX_TEXT_ANALYZE = 30000;
agentName: string,
): Promise<object> {
log.push({ agent: agentName, type: "step", message: `Calling OpenAI gpt-4o...` });
try {
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessa
import { OpenAI } from "https://esm.town/v/std/openai";
import { Hono } from "npm:hono";
// Initialize Hono for routing and OpenAI for the LLM
const app = new Hono();
const openai = new OpenAI();
/**
try {
// Call the OpenAI Chat Completions API
const completion = await openai.chat.completions.create({
model: "gpt-4o",
messages: [
return c.json(jsonData);
} catch (error) {
console.error("Error calling OpenAI or parsing JSON:", error);
// Return a structured error message if something goes wrong
return c.json({
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" },