Search
Code3,265
// superpowered_agent_platform_v3_plus_leadgen.ts// Declarative tools, parallel execution, Val Town idiomatic OpenAI & HTTP Fetch tools.// Includes original v3 demo AND new lead generation workflow.import { fetch } from "https://esm.town/v/std/fetch";import { OpenAI } from "https://esm.town/v/std/openai";// --- Core Interfaces & Logger ---// --- Tool Definitions & Registry ---type ToolType = "http_fetch" | "openai_call" | "string_template" | "custom_js_function";interface BaseToolConfig {} staticUrl?: string;}interface OpenAiCallToolConfig extends BaseToolConfig { defaultModel?: string;}};interface OpenAiDynamicParams { prompt?: string; messages?: Array<{ role: "system" | "user" | "assistant"; content: string }> | string;}const openAiCallToolHandler: ToolFunction<OpenAiDynamicParams, { result: any }, OpenAiCallToolConfig> = async ( params, staticConfig,) => { const { mandateId, taskId, log } = context; let openaiClient: OpenAI; try { openaiClient = new OpenAI(); } catch (e: any) { log("ERROR", "OpenAiCallTool", "Failed to init OpenAI client.", { originalError: e.message }); return { mandateId, correlationId: taskId, payload: { result: null }, error: "OpenAI client init failed." }; } messagesPayload = [{ role: "user", content: params.prompt }]; } else { log("ERROR", "OpenAiCallTool", "Input required: 'messages' (array/string) or 'prompt' (string)."); return { mandateId, correlationId: taskId, payload: { result: null }, error: "Missing OpenAI input." }; } apiRequestBody.max_tokens = Math.floor(params.max_tokens); log("INFO", "OpenAiCallTool", "Making OpenAI chat completion call.", { model, messagesCount: messagesPayload.length, }); log("DEBUG", "OpenAiCallTool", `Messages payload preview:`, { firstMessageContent: messagesPayload[0]?.content.substring(0, 50) + "...", }); try { const completion = await openaiClient.chat.completions.create(apiRequestBody); if (!completion?.choices?.length) { log("WARN", "OpenAiCallTool", "OpenAI response empty/unexpected.", { response: completion }); } log("SUCCESS", "OpenAiCallTool", "OpenAI call successful.", { modelUsed: completion?.model }); return { mandateId, correlationId: taskId, payload: { result: completion } }; } catch (e: any) { log("ERROR", "OpenAiCallTool", "OpenAI API call failed.", e); const errMsg = e.response?.data?.error?.message || e.error?.message || e.message || "Unknown OpenAI API error"; return { mandateId, correlationId: taskId, payload: { result: null }, error: errMsg }; } const finalLeads: { name: string; website: string; email: string; draftedEmail: string }[] = []; let openaiClient: OpenAI; try { openaiClient = new OpenAI(); } catch (e: any) { log("ERROR", "DraftEmails", "Failed to init OpenAI client.", e); return { mandateId, correlationId: taskId, payload: { finalLeads: [] }, error: "OpenAI client init failed." }; }Goal: pique interest for follow-up. Concise (under 100 words). Email body text only.`; const messages = [{ role: "user" as const, content: prompt }]; log("DEBUG", "DraftEmails", "Sending prompt to OpenAI...", { promptPreview: prompt.substring(0, 100) + "..." }); const completion = await openaiClient.chat.completions.create({ model: "gpt-4o-mini", messages, if (draftedEmail === "[Error generating email]" || !draftedEmail) { log("WARN", "DraftEmails", `OpenAI no usable content for ${lead.name}.`, { response: completion }); finalLeads.push({ ...lead, draftedEmail: "[Failed to generate email content]" }); } else { } catch (error: any) { log("ERROR", "DraftEmails", `Failed for ${lead.name}: ${error.message}`, error); finalLeads.push({ ...lead, draftedEmail: "[OpenAI API call failed]" }); } await delay(300); // Small delay between OpenAI calls } log("SUCCESS", "DraftEmails", `Email drafting complete for ${finalLeads.length} leads processed.`);const enhancedAnalysisWorkflowV3: WorkflowDefinition = { id: "enhancedAnalysisV3", description: "Fetches data, generates a summary (OpenAI or legacy), and combines results.", initialInputSchema: { required: ["userText", "userName"] }, steps: [ }, { id: "step2a_summarize_openai", toolType: "openai_call", parameters: { messages: { source: "initial", field: "userText" }, temperature: { source: "initial", field: "summaryConfig.temperature" }, }, condition: { source: "initial", field: "config.useOpenAISummarizer" }, }, { parameters: { userName: { source: "initial", field: "userName" }, aiSummary: { source: "step2a_summarize_openai", field: "result.choices[0].message.content" }, legacySummary: { source: "step2b_summarize_legacy", field: "summary" }, fetchTitle: { source: "step1_fetchData", field: "data.title" }, }, dependencies: ["step1_fetchData", "step2a_summarize_openai", "step2b_summarize_legacy"], }, ], outputMapping: { finalResult: { source: "step3_combine", field: "result" }, aiModelUsed: { source: "step2a_summarize_openai", field: "result.model" }, fetchedDataStatus: { source: "step1_fetchData", field: "status" }, },toolRegistry.registerTool("http_fetch", httpFetchToolHandler);toolRegistry.registerTool("openai_call", openAiCallToolHandler);toolRegistry.registerTool("string_template", stringTemplateToolHandler);toolRegistry.registerTool("custom_js_function", async (params, staticConfig: CustomJsFunctionToolConfig, context) => { <label for="userText">Text for summarization (Required):</label><textarea id="userText" name="userText" required rows="3">JWST images show distant galaxies.</textarea> <fieldset><legend>Summarizer Choice</legend><div class="radio-group"> <label><input type="radio" name="summarizerChoice" value="openai" checked> OpenAI</label> <label><input type="radio" name="summarizerChoice" value="legacy"> Legacy</label> </div></fieldset> const workflowStatusBox = document.getElementById('workflowStatusBox'); const workflowDefinitionClient = { id: "enhancedAnalysisV3", steps: [ { id: "step1_fetchData", description: "Fetch Data" }, { id: "step2a_summarize_openai", description: "Summarize (OpenAI)" }, { id: "step2b_summarize_legacy", description: "Summarize (Legacy)" }, { id: "step3_combine", description: "Combine Results" } ]}; customFetchUrl: fd.get('customFetchUrl') || undefined, useLegacySummarizer: choice === 'legacy', config: { useOpenAISummarizer: choice === 'openai' }, }; try { const workflowDefinitionClient = { id: "leadGenWorkflowV1", steps: [ { id: "step_search", description: "Simulate Search" }, { id: "step_scrape_emails", description: "Scrape Emails" }, { id: "step_draft_emails", description: "Draft Emails (OpenAI)" }, { id: "step_format_summary", description: "Format Summary" } ]}; ${CLIENT_SIDE_UI_SCRIPT_CONTENT}
// ---------------- Val Town Standard Library ----------------// Val Town provides limited free hosted services, including// functions for sending emails and using OpenAIimport { email } from "https://esm.town/v/std/email";import { OpenAI } from "https://esm.town/v/std/OpenAI";// --------------------- Get weather data --------------------export default async function() { // Use OpenAI provided by Val Town to get weather reccomendation // Experiment with changing the prompt const openai = new OpenAI(); let chatCompletion = await openai.chat.completions.create({ messages: [{ role: "user",
Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.### OpenAI```tsimport { 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 create a fresh table.### OpenAI```tsimport { 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" },
const prompt = `Generate a short 15-second Instagram reel script and 5 viral hashtags for the topic: "${topic}". Make the script engaging and desi style.`; const res = await fetch("https://api.openai.com/v1/chat/completions", { method: "POST", headers: { "Authorization": `Bearer ${Deno.env.get("OPENAI_API_KEY")}`, "Content-Type": "application/json", },
const prompt = `Generate a short 15-second Instagram reel script and 5 viral hashtags for the topic: "${topic}". Make the script engaging and desi style.`; const res = await fetch("https://api.openai.com/v1/chat/completions", { method: "POST", headers: { "Authorization": `Bearer ${Deno.env.get("OPENAI_API_KEY")}`, "Content-Type": "application/json", },
import { OpenAI } from "https://esm.town/v/std/openai";import { sqlite } from "https://esm.town/v/std/sqlite";import nlp from "npm:compromise";}const openai = new OpenAI();const app = express();app.use(express.json()); // 1. Parse intent + slots // const prompt = buildIntentPrompt(text); // const completion = await openai.chat.completions.create({ // messages: [ // { role: "system", content: prompt }, const rows = transformRows<Item>(result); const prompt = buildKnowledgePrompt(text, rows); const completion = await openai.chat.completions.create({ messages: [ { role: "system", content: prompt },
/** * Transforms a Zod schema into a format suitable for OpenAI by: * - Adding additionalProperties: false to all objects * - Making all fields required * - Removing validation constraints that OpenAI might struggle with * * Specifically removes: * @returns A new Zod schema with modified properties */export function transformSchemaForOpenAI<T extends ZodType>(schema: T): T { // Helper to process each schema type function processSchema(schema: ZodTypeAny): ZodTypeAny { // For unions, just convert to the first type for simplicity // This is a simplification that might lose some information // but ensures OpenAI has a concrete type to work with return processSchema(schema._def.options[0]) } standardization: z.string().describe("If the value has confidence > 0.8 keep pass the original value as is, Otherwise pass in following format, suitable for tooltip: UpdatedStandardValue=ReasonBehindUpdation") })// Create a simplified schema for OpenAI with fewer parameters// This addresses the 100 parameter limit in OpenAI's response_formatexport const SimplifiedResumeSchema = z.object({ personalInfo: z.object({})// Example of how to use the transformSchemaForOpenAI function:// This creates a version of SimplifiedResumeSchema that's suitable for OpenAIexport const OpenAICompatibleResumeSchema = transformSchemaForOpenAI(SimplifiedResumeSchema)
import { OpenAI } from "https://esm.town/v/std/openai";export default async function(req: Request): Promise<Response> { }); } const openai = new OpenAI(); try { } const stream = await openai.chat.completions.create(body); if (!body.stream) {
Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to create a fresh table.### OpenAI```tsimport { 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" },
reconsumeralization
import { OpenAI } from "https://esm.town/v/std/openai";
import { sqlite } from "https://esm.town/v/stevekrouse/sqlite";
/**
* Practical Implementation of Collective Content Intelligence
* Bridging advanced AI with collaborative content creation
*/
exp
kwhinnery_openai
lost1991
import { OpenAI } from "https://esm.town/v/std/openai";
export default async function(req: Request): Promise<Response> {
if (req.method === "OPTIONS") {
return new Response(null, {
headers: {
"Access-Control-Allow-Origin": "*",
No docs found