mandateagent_ecosystem.ts29 matches
4import { AgentContext, AgentInput, AgentOutput } from "https://esm.town/v/salon/mandate/interfaces.ts";
5import { fetch } from "https://esm.town/v/std/fetch";
6import { OpenAI } from "https://esm.town/v/std/openai";
7// If Deno.env is used, ensure it's for Val Town secrets if possible or clearly noted.
8// For direct Deno.env.get('OPENAI_API_KEY'), it relies on the Val Town environment variable being set.
9// The std/openai library usually handles API key abstraction using user's Val Town secrets.
1011// Your provided summarizerAgent
27}
2829const openai = new OpenAI(); // Using OpenAI client as per your example
3031log("INFO", "SummarizerAgent", "Generating summary with OpenAI...");
32const completion = await openai.chat.completions.create({
33model: "gpt-4o-mini", // Explicitly setting a model
34messages: [
4546if (summary === "Could not generate summary.") {
47log("WARN", "SummarizerAgent", "OpenAI did not return a valid summary content.");
48}
49200// Your provided combinerAgent (not directly used in the 12-step orchestrator, but kept for reference)
201export async function combinerAgent(
202// ... (combinerAgent code as you provided, also updating its OpenAI call) ...
203input: AgentInput<{
204summary?: string;
254}
255256const openai = new OpenAI(); // Using OpenAI client as per your example
257log("INFO", "CombinerAgent", "Combining text with OpenAI...");
258const completion = await openai.chat.completions.create({
259model: "gpt-4o-mini", // Explicitly setting a model
260messages: [
274const combined = completion.choices[0]?.message?.content?.trim() ?? "Could not combine information.";
275if (combined === "Could not combine information.")
276log("WARN", "CombinerAgent", "OpenAI did not return valid combined content.");
277log("SUCCESS", "CombinerAgent", "Combined successfully");
278return { mandateId, correlationId: taskId, payload: { combined } };
336const { userQuery } = input.payload;
337log("INFO", "ConfigurationAgent", `Processing query: ${userQuery}`);
338const openai = new OpenAI();
339340const systemPrompt =
347348try {
349const completion = await openai.chat.completions.create({
350model: "gpt-4o-mini",
351messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userQuery }],
483const { log } = context;
484const { articles, topic, keywords } = input.payload;
485const openai = new OpenAI();
486let relevantArticles: FetchedArticle[] = [];
487log("INFO", "RelevanceAssessmentAgent", `Assessing relevance for ${articles.length} articles on topic: ${topic}`);
496let assessment = { isRelevant: false, rationale: "LLM assessment failed or unclear." };
497try {
498const completion = await openai.chat.completions.create({
499model: "gpt-4o-mini",
500messages: [{ role: "system", content: "You are a relevance assessor. Output JSON." }, {
559): Promise<AgentOutput<{ articlesWithSentiment: FetchedArticle[] }>> {
560const { log } = context;
561const openai = new OpenAI();
562let articlesWithSentiment: FetchedArticle[] = [];
563if (!input.payload.articles)
572let sentimentScore: FetchedArticle["sentimentScore"] = 0.0;
573try {
574const completion = await openai.chat.completions.create({
575model: "gpt-4o-mini",
576messages: [{ role: "system", content: "You are a sentiment analysis expert. Output JSON." }, {
607): Promise<AgentOutput<{ articlesWithThemes: FetchedArticle[] }>> {
608const { log } = context;
609const openai = new OpenAI();
610let articlesWithThemes: FetchedArticle[] = [];
611log(
621let themeResult: { themes: string[]; entities: FetchedArticle["entities"] } = { themes: [], entities: [] };
622try {
623const completion = await openai.chat.completions.create({
624model: "gpt-4o-mini",
625messages: [{ role: "system", content: "You are a thematic/NER expert. Output JSON." }, {
653const { log } = context;
654const { articlesWithThemes, topic, historicalContextSummary } = input.payload;
655const openai = new OpenAI();
656log(
657"INFO",
676let trendReport: any = { dominantSentiment: "N/A", keyThemes: [], emergingPatterns: "Not analyzed." };
677try {
678const completion = await openai.chat.completions.create({
679model: "gpt-4o-mini",
680messages: [{ role: "system", content: "Trend analysis expert. Output JSON." }, {
697let anomalyReport: any = { anomaliesFound: false, anomalyDetails: [] };
698try {
699const completion = await openai.chat.completions.create({
700model: "gpt-4o-mini",
701messages: [{ role: "system", content: "Anomaly detection expert. Output JSON." }, {
724const { log } = context;
725const { trendReport, anomalyReport, config, articlesCount } = input.payload;
726const openai = new OpenAI();
727log("INFO", "InsightGenerationAgent", `Generating insights for topic: ${config.topic}`);
728const contextSummary =
737let insights: string[] = ["No specific insights generated."];
738try {
739const completion = await openai.chat.completions.create({
740model: "gpt-4o-mini",
741messages: [{ role: "system", content: "Strategic analyst providing concise insights." }, {
852853log("INFO", "ReportCompilationAgent", `Compiling report for topic: ${config.topic}`); // Directly use 'config'
854const openai = new OpenAI(); // Ensure API key is configured via environment variables or client options
855856// The agent code used 'relevantArticles'. If 'articlesWithThemes' is the correct data source
882let finalReport = "Report generation failed.";
883try {
884const completion = await openai.chat.completions.create({
885model: "gpt-4o-mini",
886messages: [
912const { log } = context;
913const { anomalyReport, insights, config } = input.payload;
914const openai = new OpenAI();
915let criticalInfo = "";
916if (anomalyReport?.anomaliesFound && anomalyReport.anomalyDetails.length > 0) {
932let alertMessage: string | undefined = undefined;
933try {
934const completion = await openai.chat.completions.create({
935model: "gpt-4o-mini",
936messages: [{ role: "system", content: "Alert generation specialist." }, { role: "user", content: prompt }],
stevenns.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" },
3import { validator } from "https://esm.sh/hono@4.3.7/validator";
4// Using @valtown/sqlite
5import { OpenAI } from "https://esm.town/v/std/openai?v=1";
6import { Batch, sqlite, Statement } from "https://esm.town/v/std/sqlite?v=4";
7190191async function draftColdEmail(
192openai: OpenAI,
193businessName: string | undefined,
194websiteUrl: string,
241242try {
243const chatCompletion = await openai.chat.completions.create({
244model: "gpt-3.5-turbo",
245messages: [{ role: "user", content: prompt }],
250const responseText = chatCompletion.choices[0]?.message?.content?.trim();
251if (!responseText) {
252await updateLeadStatus(leadId, "error_drafting_empty_response", {}, "OpenAI returned empty response");
253return null;
254}
279} catch (error) {
280console.error(`Error drafting email for ${emailAddress} (lead ${leadId}):`, error);
281await updateLeadStatus(leadId, "error_drafting", {}, `OpenAI API error: ${error.message}`);
282return null;
283}
286async function processJob(jobId: string, searchQuery: string) {
287await updateJobStatus(jobId, "processing_search");
288const openaiApiKey = Deno.env.get("openai");
289if (!openaiApiKey) {
290console.error("OpenAI API key secret 'openai' is not set.");
291await updateJobStatus(jobId, "failed_config", "OpenAI API key not configured.");
292return;
293}
294const openai = new OpenAI({ apiKey: openaiApiKey });
295296const websites = await searchWebsites(searchQuery, jobId);
327const emailAddress = await extractEmailsFromWebsite(site.url, leadId);
328if (emailAddress) {
329await draftColdEmail(openai, truncatedBusinessName, site.url, emailAddress, searchQuery, leadId);
330}
331}
StarterPackFeeds.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" },
blog-cloneget-old-posts.ts5 matches
198},
199{
200"title": "An Introduction to OpenAI fine-tuning",
201"slug": "an-introduction-to-openai-fine-tuning",
202"link": "/blog/an-introduction-to-openai-fine-tuning",
203"description": "How to customize OpenAI to your liking",
204"pubDate": "Fri, 25 Aug 2023 00:00:00 GMT",
205"author": "Steve Krouse",
417"slug": "val-town-newsletter-16",
418"link": "/blog/val-town-newsletter-16",
419"description": "Our seed round, growing team, Codeium completions, @std/openai, and more",
420"pubDate": "Mon, 22 Apr 2024 00:00:00 GMT",
421"author": "Steve Krouse",
blogget-old-posts.ts5 matches
198},
199{
200"title": "An Introduction to OpenAI fine-tuning",
201"slug": "an-introduction-to-openai-fine-tuning",
202"link": "/blog/an-introduction-to-openai-fine-tuning",
203"description": "How to customize OpenAI to your liking",
204"pubDate": "Fri, 25 Aug 2023 00:00:00 GMT",
205"author": "Steve Krouse",
417"slug": "val-town-newsletter-16",
418"link": "/blog/val-town-newsletter-16",
419"description": "Our seed round, growing team, Codeium completions, @std/openai, and more",
420"pubDate": "Mon, 22 Apr 2024 00:00:00 GMT",
421"author": "Steve Krouse",
French_Bulldogmain.tsx5 matches
1import { OpenAI } from "https://esm.town/v/std/openai";
2import { telegramSendMessage } from "https://esm.town/v/vtdocs/telegramSendMessage?v=5";
3import {
15console.log(`received: ${text}`)
16if (text) {
17const response = await translateWithOpenAI(text);
18console.log(`translated to: ${response}`);
19ctx.reply(response);
333435async function translateWithOpenAI(text: string) {
36const openai = new OpenAI();
37const completion = await openai.chat.completions.create({
38messages: [
39{
1import { OpenAI } from "https://esm.town/v/std/openai";
2import { telegramSendMessage } from "https://esm.town/v/vtdocs/telegramSendMessage?v=5";
3import {
15console.log(`received: ${text}`)
16if (text) {
17const response = await translateWithOpenAI(text);
18console.log(`translated to: ${response}`);
19ctx.reply(response);
333435async function translateWithOpenAI(text: string) {
36const openai = new OpenAI();
37const completion = await openai.chat.completions.create({
38messages: [
39{
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 = `
ArabicChef_Botmain.tsx5 matches
1import { OpenAI } from "https://esm.town/v/std/openai";
2import { telegramSendMessage } from "https://esm.town/v/vtdocs/telegramSendMessage?v=5";
3import {
15console.log(`received: ${text}`)
16if (text) {
17const response = await translateWithOpenAI(text);
18console.log(`translated to: ${response}`);
19ctx.reply(response);
333435async function translateWithOpenAI(text: string) {
36const openai = new OpenAI();
37const completion = await openai.chat.completions.create({
38messages: [
39{