1import { email } from "https://esm.town/v/std/email";
2import { OpenAI } from "https://esm.town/v/std/openai";
3import { JSDOM } from "npm:jsdom";
4import { NodeHtmlMarkdown, NodeHtmlMarkdownOptions } from "npm:node-html-markdown";
16);
1718const openai = new OpenAI();
19console.log(trendingMarkdown);
2021const completion = await openai.chat.completions.create({
22messages: [
23{
125if (request.method === "POST") {
126try {
127const { OpenAI } = await import("https://esm.town/v/std/openai");
128const openai = new OpenAI();
129130const formData = await request.formData();
138const cvText = new TextDecoder().decode(cvBuffer);
139140const completion = await openai.chat.completions.create({
141messages: [
142{
discord-botapi-server.js9 matches
1import express from 'express';
2import { getMessages, getLinks, getCategories, updateLinkCategory } from './database.js';
3import { Configuration, OpenAIApi } from 'openai';
4import 'dotenv/config';
58app.use(express.json());
910// Initialize OpenAI for AI-powered queries
11const configuration = new Configuration({
12apiKey: process.env.OPENAI_API_KEY,
13});
14const openai = new OpenAIApi(configuration);
1516/**
17* Function to analyze messages with OpenAI
18* @param {Array} messages - Array of message objects
19* @param {string} query - User query to analyze messages with
20* @returns {Object} - OpenAI response
21*/
22async function analyzeMessagesWithAI(messages, query) {
23try {
24// Format messages for OpenAI
25const formattedConversation = messages.map(msg => {
26const author = msg.author_id === process.env.DISCORD_USER_ID ? 'You' : 'Partner';
37`;
38
39// Call OpenAI API
40const response = await openai.createCompletion({
41model: "gpt-3.5-turbo-instruct",
42prompt: prompt,
discord-botquery-service.js1 match
115const links = getLinks(linkFilters);
116
117// If no specific categories, use OpenAI to help filter relevant links
118if ((!categories || categories.length === 0) && links.length > 0) {
119const relevantLinks = await filterRelevantLinks(links, query);
discord-bot.env.example2 matches
5SPOUSE_USER_ID=spouse_user_id_here
67# OpenAI API key (for AI-powered querying)
8OPENAI_API_KEY=your_openai_api_key_here
910# Val.town settings
discord-botREADME.md3 matches
25- Node.js 16+ and npm
26- Discord account with Bot token
27- OpenAI API key (for AI-powered queries)
28- Val.town account (for deployment)
2951- `DISCORD_USER_ID`: Your Discord user ID
52- `SPOUSE_USER_ID`: Your partner's Discord user ID
53- `OPENAI_API_KEY`: Your OpenAI API key
54555. Initialize the database
146147- Discord.js for Discord API integration
148- OpenAI for AI-powered querying
149- Val.town for hosting and scheduling
150- Better-SQLite3 for database management
discord-bot.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" },
discord-botDISCORD_BOT_SETUP.md3 matches
57```
5859## 7. Get OpenAI API Key
60611. Go to [OpenAI's website](https://platform.openai.com/)
622. Sign up or log in
633. Navigate to the API keys section
666. Add it to your `.env` file:
67```
68OPENAI_API_KEY=your_openai_api_key_here
69```
70
6* Uses 'npm:pdf.js-extract' for direct PDF text extraction.
7* Serves HTML UI & API endpoint from the same Val.
8* OpenAI import is dynamically done inside the main server function.
9*
10* Based on structure from multi-agent support simulation example.
11* Assumes 'openai' secret is set in Val Town environment variables.
12*
13* Last Updated: 2025-05-01 (Dashboard UI, Localization, Animation Integration)
950export default async function(req: Request) {
951// --- Dynamic Imports (Inside Handler) ---
952const { OpenAI } = await import("https://esm.town/v/std/openai");
953const { z } = await import("npm:zod");
954const { fetch } = await import("https://esm.town/v/std/fetch");
990}
991992// --- Helper Function: Call OpenAI API (Unchanged) ---
993async function callOpenAI(
994openai: OpenAI,
995systemPrompt: string,
996userMessage: string,
999): Promise<{ role: "assistant" | "system"; content: string | object }> {
1000try {
1001const response = await openai.chat.completions.create({
1002model: model,
1003messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }],
1011return { role: "assistant", content: JSON.parse(content) };
1012} catch (parseError) {
1013console.error("OpenAI JSON Parse Error:", parseError, "Raw Content:", content);
1014throw new Error(`AI response was not valid JSON. Raw: ${content.substring(0, 150)}...`);
1015}
1016} else { return { role: "assistant", content: content }; }
1017} catch (error) {
1018console.error(`OpenAI API call failed. ExpectJSON: ${expectJson}. Error:`, error);
1019let errorMessage = "Error communicating with AI model.";
1020if (error.message) { errorMessage += ` Details: ${error.message}`; }
1021// Check for specific error types if needed (e.g., rate limits, auth)
1022if (error.status === 401) errorMessage = "Authentication error with OpenAI API. Check your secret key.";
1023if (error.status === 429) errorMessage = "OpenAI API rate limit exceeded. Please try again later.";
10241025return { role: "system", content: errorMessage };
1112log: LogEntry[],
1113): Promise<LogEntry[]> { // Returns the completed log array
1114const openai = new OpenAI(); // Assumes API key is in environment variables
11151116log.push({ agent: "System", type: "step", message: "Starting analysis workflow." });
1217// --- 2. Content Analysis ---
1218log.push({ agent: "System", type: "step", message: "Starting Content Analysis..." });
1219const analysisResponse = await callOpenAI(openai, contentAnalysisSystemPrompt, truncatedText, "gpt-4o", true); // Use gpt-4o
1220let analysisResult: AnalysisResult | null = null;
1221if (analysisResponse.role === "assistant" && typeof analysisResponse.content === "object") {
1237// --- 3. Citation Extraction ---
1238log.push({ agent: "System", type: "step", message: "Starting Citation Extraction..." });
1239const citationResponse = await callOpenAI(openai, citationExtractionSystemPrompt, truncatedText, "gpt-4o", true); // Use gpt-4o
1240let extractedCitations: Citation[] = [];
1241if (
1267message: \`AI response was not the expected JSON format. Received: \${JSON.stringify(citationResponse.content).substring(0, 200)}...\`,
1268});
1269} else { // System error from callOpenAI
1270log.push({ agent: "Citation Extraction Agent", type: "error", message: citationResponse.content });
1271}
myanythingmain.tsx3 matches
125if (request.method === 'POST') {
126try {
127const { OpenAI } = await import("https://esm.town/v/std/openai");
128const openai = new OpenAI();
129130const formData = await request.formData();
138const cvText = new TextDecoder().decode(cvBuffer);
139140const completion = await openai.chat.completions.create({
141messages: [
142{