stevens-openaigenerateFunFacts.ts8 matches
2import { nanoid } from "https://esm.sh/nanoid@5.0.5";
3import { sqlite } from "https://esm.town/v/stevekrouse/sqlite";
4import { OpenAI } from "npm:openai";
56const TABLE_NAME = `memories`;
6364// -----------------------------------------------------------------------------
65// LLM: generate seven new fun‑facts (OpenAI)
66// -----------------------------------------------------------------------------
67async function generateFunFacts(previousFacts: { date: string; text: string }[]) {
68const apiKey = Deno.env.get("OPENAI_API_KEY");
69if (!apiKey) {
70console.error("OPENAI_API_KEY is not configured.");
71return [];
72}
7374const openai = new OpenAI({ apiKey });
7576// Build auxiliary strings for the prompt
113114try {
115const completion = await openai.chat.completions.create({
116model: "gpt-4o-mini", // inexpensive; change if needed
117max_tokens: 800,
145}
146} catch (err) {
147console.error("OpenAI error while generating fun facts:", err);
148return [];
149}
211212// -----------------------------------------------------------------------------
213// Manual test run (deno run funFactsOpenAI.ts)
214// -----------------------------------------------------------------------------
215if (import.meta.main) {
stevens-openaigetWeather.ts6 matches
1import { getWeather, WeatherResponse } from "https://esm.town/v/geoffreylitt/getWeather";
2import { sqlite } from "https://esm.town/v/stevekrouse/sqlite";
3import { OpenAI } from "npm:openai";
45const TABLE_NAME = `memories`;
2223/**
24* Call OpenAI Chat Completions to compress a single day's forecast
25* into a <25‑word sentence.
26*/
27async function generateConciseWeatherSummary(weatherDay: ReturnType<typeof summarizeWeather>[number]) {
28const apiKey = Deno.env.get("OPENAI_API_KEY");
29if (!apiKey) {
30console.error("OPENAI_API_KEY is not configured.");
31return null;
32}
3334const openai = new OpenAI({ apiKey });
3536const systemPrompt = `You are a weather forecaster. Create a very concise summary of a day's forecast.`;
4142try {
43const completion = await openai.chat.completions.create({
44model: "gpt-4o-mini", // cheap & fast; change if desired
45max_tokens: 100,
stevens-openaisendDailyBrief.ts10 matches
1import { Bot } from "https://deno.land/x/grammy@v1.35.0/mod.ts";
2import { DateTime } from "https://esm.sh/luxon@3.4.4";
3import { OpenAI } from "npm:openai";
4import { backstory } from "../backstory.ts";
5import { BOT_SENDER_ID, BOT_SENDER_NAME, storeChatMessage } from "../importers/handleTelegramMessage.ts";
910/**
11* Generate the daily briefing using OpenAI Chat Completions
12*/
13async function generateBriefingContent(
14openai: OpenAI,
15memories: Awaited<ReturnType<typeof getRelevantMemories>>,
16today: DateTime,
77};
7879// --------------- OPENAI CALL ----------------- //
80const completion = await openai.chat.completions.create({
81model: "gpt-4o", // adjust as desired
82max_tokens: 3000,
97) {
98// Get API keys from environment
99const apiKey = Deno.env.get("OPENAI_API_KEY");
100const telegramToken = Deno.env.get("TELEGRAM_TOKEN");
101106107if (!apiKey) {
108console.error("OPENAI_API_KEY is not configured.");
109return;
110}
120}
121122// Initialize OpenAI client
123const openai = new OpenAI({ apiKey });
124125// Initialize Telegram bot
140// Generate briefing content
141const content = await generateBriefingContent(
142openai,
143memories,
144today,
stevens-openai.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" },
JimeluStevens.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" },
valreadmegeneratormain.tsx3 matches
177}
178179const { OpenAI } = await import("https://esm.town/v/std/openai");
180const openai = new OpenAI();
181182const valTownClient = new ValTown({
197198try {
199const completion = await openai.chat.completions.create({
200model: "gpt-4o",
201messages: [
valreadmegeneratorREADME.md1 match
43- **Deno:** The server-side environment.
44- **ValTown SDK:** Integrated to fetch Val details.
45- **OpenAI GPT-4:** To generate natural language README content.
46- **JavaScript Modules (ESM):** For seamless module imports.
47
stevensDemo.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" },
stevensDemo.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 { sqlite } from "https://esm.town/v/stevekrouse/sqlite";
3import * as ta from "npm:technicalindicators";
362}
363364async function callOpenAI(
365Â systemPrompt: string,
366Â userMessage: string,
372): Promise<{ role: "assistant" | "system"; content: string }> {
373Â const callId = Math.random().toString(36).substring(2, 8);
374Â const logPfx = `OpenAI Call [${agentName} ${taskId.split("-")[1] || taskId} ${callId}]`;
375Â try {
376Â log("DEBUG", agentName, `${logPfx}: Initiating (${model}, JSON: ${isJsonOutputRequired})...`);
377Â const openai = new OpenAI();
378Â const res = await openai.chat.completions.create({
379Â Â model,
380Â Â messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }],
384Â const content = res.choices?.[0]?.message?.content;
385Â if (!content) {
386Â Â log("ERROR", agentName, `${logPfx}: OpenAI returned empty/invalid response.`);
387Â Â throw new Error("Invalid/empty AI response.");
388Â }
394Â let code = err.status || (err.response ? err.response.status : null);
395Â const errData = err.response?.data || err.error || err.response || err;
396Â if (errData?.message) { errMsg = `OpenAI Err (${code || "?"}) via ${agentName}: ${errData.message}`; }
397Â else if (errData?.error?.message) { errMsg = `OpenAI Err (${code || "?"}) via ${agentName}: ${errData.error.message}`; }
398Â else if (err.message) { errMsg += ` Details: ${err.message}`; }
399Â else { try { errMsg += ` Unknown err: ${JSON.stringify(errData)}`; } catch { errMsg += " Unknown non-serializable err."; }}
402Â else if (code === 400) errMsg += " (ACTION: Bad request/prompt issue)";
403Â else if (err.code === "ENOTFOUND" || err.code === "ECONNREFUSED" || err.cause?.code === "UND_ERR_CONNECT_TIMEOUT") errMsg += " (ACTION: Network error)";
404Â else if (code >= 500) errMsg += " (ACTION: OpenAI server issue)";
405Â const escapedErr = errMsg.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n");
406Â if (isJsonOutputRequired) {
659Â const taskId = task.taskId;
660Â log("INFO", agentName, `Task ${taskId}. Processing goals. Hash: ${hashCode(JSON.stringify(task.payload))}`);
661Â const result = await callOpenAI(
662Â tickerSuggestionAgentSystemPrompt,
663Â JSON.stringify(task.payload),
999Â },
1000Â });
1001Â const result = await callOpenAI(
1002Â tickerInterpretationAgentSystemPrompt,
1003Â input,
1111Â pastPerformanceContext: pastPerformanceContext ?? "N/A",
1112Â });
1113Â const result = await callOpenAI(
1114Â synthesisChartingDataAgentSystemPrompt,
1115Â input,