1import { fetch } from "https://esm.town/v/std/fetch";
2import { OpenAI } from "https://esm.town/v/std/openai";
3import { z } from "npm:zod";
4
433}
434
435async function callOpenAI(sysP: string, userP: string, mid: string, tid: string, log: LogFn): Promise<string | null> {
436 log("DB", "OpenAI", `Call tid=${tid}`, { sL: sysP.length, uL: userP.length }, mid, tid);
437 try { // @ts-ignore
438 const oai = new OpenAI();
439 const comp = await oai.chat.completions.create({
440 model: "gpt-4o-mini",
446 const usg = comp.usage;
447 if (!resT) {
448 log("WN", "OpenAI", `No text tid=${tid}.`, { usg, fin: comp.choices[0]?.finish_reason }, mid, tid);
449 return null;
450 }
451 log("IN", "OpenAI", `OK tid=${tid}`, { rL: resT.length, usg, fin: comp.choices[0]?.finish_reason }, mid, tid);
452 return resT.trim();
453 } catch (err: any) {
461 st: err.status,
462 };
463 log("ER", "OpenAI", `Fail tid=${tid}:${err.message}`, { e: eD }, mid, tid);
464 throw new Error(
465 `OpenAI API Call Failed: ${err.message}`
466 + (err.code ? ` (Code:${err.code}, Status:${err.status})` : (err.status ? ` (Status:${err.status})` : "")),
467 );
765 }
766 const filledUserPrompt = Utils.fillPromptTemplate(userPrompt, params);
767 const rawOpenAIResponse = await callOpenAI(systemPrompt, filledUserPrompt, mid, tid, logFn);
768 if (!rawOpenAIResponse) {
769 logFn("WN", agentConfig.name, `OpenAI call returned no content, tid=${tid}.`, {}, mid, tid);
770 return { mid, cid: tid, p: {} as TOD, e: `${agentConfig.name} Error: AI returned no content.` };
771 }
772 let outputData: TOD;
773 try {
774 outputData = agentConfig.outputParser(rawOpenAIResponse);
775 } catch (parseError: any) {
776 logFn(
778 agentConfig.name,
779 `Output parsing failed, tid=${tid}. M: ${parseError.message}`,
780 { rawResponsePreview: rawOpenAIResponse.slice(0, 500) },
781 mid,
782 tid,
6export async function emailValHandler(receivedEmail) {
7 const llmApiUrl = "https://api.anthropic.com/v1/messages";
8 const apiKey = Deno.env.get("ANTHROPIC_API_KEY"); // replace this entire line with your OpenAI API key as a string, e.g., "sk-123..." or use environment variable: https://docs.val.town/reference/environment-variables/
9 const model = "claude-opus-4-20250514";
10
35 const prompt = generatePrompt(receivedEmail, pdfTexts, emailText);
36
37 // step 4: send prompt to openai
38 const aiResponse = await sendRequestToAI(prompt, llmApiUrl, apiKey, model);
39
40 // log the openai response
41 console.log("openai response:", aiResponse);
42
43 // step 5: send the response back via email
97}
98
99// helper function to generate a prompt for openai
100function generatePrompt(email, pdfTexts, emailText) {
101 // extract the first name from the 'from' field if it exists
121}
122
123// helper function to send a request to openai
124async function sendRequestToAI(prompt, llmApiUrl, apiKey, model) {
125 try {
126 // prepare the openai messages payload
127 const messages = [
128 {
148 };
149
150 // send the request to openai
151 const response = await fetch(llmApiUrl, {
152 method: "POST",
161 const data = await response.json();
162 console.log(data);
163 return data.choices[0]?.message?.content || "no response from openai.";
164 } catch (err) {
165 console.error("error in sendRequestToAI:", err);
5// main controller function
6export async function emailValHandler(receivedEmail) {
7 const openaiUrl = "https://api.openai.com/v1/chat/completions";
8 const apiKey = Deno.env.get("OPENAI_KEY"); // replace this entire line with your OpenAI API key as a string, e.g., "sk-123..." or use environment variable: https://docs.val.town/reference/environment-variables/
9 const model = "gpt-4o-mini";
10
11 if (!apiKey) {
12 throw new Error(
13 "OPENAI_KEY environment variable is not set. Please set it or replace this line with your API key.",
14 );
15 }
35 const prompt = generatePrompt(receivedEmail, pdfTexts, emailText);
36
37 // step 4: send prompt to openai
38 const openaiResponse = await sendRequestToOpenAI(prompt, openaiUrl, apiKey, model);
39
40 // log the openai response
41 console.log("openai response:", openaiResponse);
42
43 // step 5: send the response back via email
44 await sendResponseByEmail(receivedEmail.from, openaiResponse);
45
46 console.log("response email sent.");
97}
98
99// helper function to generate a prompt for openai
100function generatePrompt(email, pdfTexts, emailText) {
101 // extract the first name from the 'from' field if it exists
121}
122
123// helper function to send a request to openai
124async function sendRequestToOpenAI(prompt, openaiUrl, apiKey, model) {
125 try {
126 // prepare the openai messages payload
127 const messages = [
128 {
142 };
143
144 // send the request to openai
145 const response = await fetch(openaiUrl, {
146 method: "POST",
147 body: JSON.stringify(body),
154 // parse the response
155 const data = await response.json();
156 return data.choices[0]?.message?.content || "no response from openai.";
157 } catch (err) {
158 console.error("error in sendRequestToOpenAI:", err);
159 return "error processing your request.";
160 }