Search
Code3,285
* Legal AI Document Analysis (Single Val Version with PDF Upload & Dashboard Style) * Ingests documents (URL, Text, PDF Upload), takes a user-defined legal task query, * and uses a Legal AI Agent (via OpenAI) to analyze the content. * The Legal AI Agent outputs a standardized JSON structure. * Uses 'npm:pdf.js-extract' for direct PDF text extraction within the Val.export default async function(req: Request) { // --- Dynamic Imports (Inside Handler) --- const { OpenAI } = await import("https://esm.town/v/std/openai"); const { z } = await import("npm:zod"); // For potential future robust input validation on server const { fetch } = await import("https://esm.town/v/std/fetch"); } // --- Helper Function: Call OpenAI API --- async function callOpenAI( openai: OpenAI, systemPrompt: string, userMessage: string, // This will be the document text ): Promise<object | string> { // Return type can be object if JSON, or string if error try { const response = await openai.chat.completions.create({ model: model, messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }], return JSON.parse(content); } catch (parseError) { console.error("OpenAI JSON Parse Error:", parseError, "Raw Content:", content); // Return the raw content if parsing fails, for debugging, wrapped as an error object return { } } catch (error) { console.error(`OpenAI API call failed. Error:`, error); let errorMessage = "Error communicating with AI model."; if (error.message) { errorMessage += ` Details: ${error.message}`; } log: LogEntry[], ): Promise<{ finalResult?: LegalAIResponse | object; log: LogEntry[] }> { const openai = new OpenAI(); // Assumes OPENAI_API_KEY is in environment log.push({ agent: "System", type: "step", message: "Starting Legal AI analysis workflow." }); finalSystemPrompt = finalSystemPrompt.replace("%%INPUT_SOURCE_DESCRIPTION%%", input.inputSourceDescription); const aiResponse = await callOpenAI(openai, finalSystemPrompt, truncatedText, "gpt-4o", true); // Expect JSON if (typeof aiResponse === "object" && (aiResponse as any).error) { // Error from callOpenAI helper (API or parsing) log.push({ agent: "Legal AI Agent", log.push({ agent: "System", type: "final", message: "Workflow finished successfully." }); return { finalResult: aiResponse as LegalAIResponse, log }; } else { // Should not happen if expectJson is true and no error object from callOpenAI log.push({ agent: "Legal AI Agent",
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" },
* Legal AI Document Analysis (Single Val Version with PDF Upload & Dashboard Style) * Ingests documents (URL, Text, PDF Upload), takes a user-defined legal task query, * and uses a Legal AI Agent (via OpenAI) to analyze the content. * The Legal AI Agent outputs a standardized JSON structure. * Uses 'npm:pdf.js-extract' for direct PDF text extraction within the Val.export default async function(req: Request) { // --- Dynamic Imports (Inside Handler) --- const { OpenAI } = await import("https://esm.town/v/std/openai"); const { z } = await import("npm:zod"); // For potential future robust input validation on server const { fetch } = await import("https://esm.town/v/std/fetch"); } // --- Helper Function: Call OpenAI API --- async function callOpenAI( openai: OpenAI, systemPrompt: string, userMessage: string, // This will be the document text ): Promise<object | string> { // Return type can be object if JSON, or string if error try { const response = await openai.chat.completions.create({ model: model, messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }], return JSON.parse(content); } catch (parseError) { console.error("OpenAI JSON Parse Error:", parseError, "Raw Content:", content); // Return the raw content if parsing fails, for debugging, wrapped as an error object return { } } catch (error) { console.error(`OpenAI API call failed. Error:`, error); let errorMessage = "Error communicating with AI model."; if (error.message) { errorMessage += ` Details: ${error.message}`; } log: LogEntry[], ): Promise<{ finalResult?: LegalAIResponse | object; log: LogEntry[] }> { const openai = new OpenAI(); // Assumes OPENAI_API_KEY is in environment log.push({ agent: "System", type: "step", message: "Starting Legal AI analysis workflow." }); finalSystemPrompt = finalSystemPrompt.replace("%%INPUT_SOURCE_DESCRIPTION%%", input.inputSourceDescription); const aiResponse = await callOpenAI(openai, finalSystemPrompt, truncatedText, "gpt-4o", true); // Expect JSON if (typeof aiResponse === "object" && (aiResponse as any).error) { // Error from callOpenAI helper (API or parsing) log.push({ agent: "Legal AI Agent", log.push({ agent: "System", type: "final", message: "Workflow finished successfully." }); return { finalResult: aiResponse as LegalAIResponse, log }; } else { // Should not happen if expectJson is true and no error object from callOpenAI log.push({ agent: "Legal AI Agent",
* Legal AI Document Analysis (Single Val Version with PDF Upload & Dashboard Style) * Ingests documents (URL, Text, PDF Upload), takes a user-defined legal task query, * and uses a Legal AI Agent (via OpenAI) to analyze the content. * The Legal AI Agent outputs a standardized JSON structure. * Uses 'npm:pdf.js-extract' for direct PDF text extraction within the Val.export default async function(req: Request) { // --- Dynamic Imports (Inside Handler) --- const { OpenAI } = await import("https://esm.town/v/std/openai"); const { z } = await import("npm:zod"); // For potential future robust input validation on server const { fetch } = await import("https://esm.town/v/std/fetch"); } // --- Helper Function: Call OpenAI API --- async function callOpenAI( openai: OpenAI, systemPrompt: string, userMessage: string, // This will be the document text ): Promise<object | string> { // Return type can be object if JSON, or string if error try { const response = await openai.chat.completions.create({ model: model, messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }], return JSON.parse(content); } catch (parseError) { console.error("OpenAI JSON Parse Error:", parseError, "Raw Content:", content); // Return the raw content if parsing fails, for debugging, wrapped as an error object return { } } catch (error) { console.error(`OpenAI API call failed. Error:`, error); let errorMessage = "Error communicating with AI model."; if (error.message) { errorMessage += ` Details: ${error.message}`; } log: LogEntry[], ): Promise<{ finalResult?: LegalAIResponse | object; log: LogEntry[] }> { const openai = new OpenAI(); // Assumes OPENAI_API_KEY is in environment log.push({ agent: "System", type: "step", message: "Starting Legal AI analysis workflow." }); finalSystemPrompt = finalSystemPrompt.replace("%%INPUT_SOURCE_DESCRIPTION%%", input.inputSourceDescription); const aiResponse = await callOpenAI(openai, finalSystemPrompt, truncatedText, "gpt-4o", true); // Expect JSON if (typeof aiResponse === "object" && (aiResponse as any).error) { // Error from callOpenAI helper (API or parsing) log.push({ agent: "Legal AI Agent", log.push({ agent: "System", type: "final", message: "Workflow finished successfully." }); return { finalResult: aiResponse as LegalAIResponse, log }; } else { // Should not happen if expectJson is true and no error object from callOpenAI log.push({ agent: "Legal AI Agent",
- [**We at Val Town**](https://www.val.town/u/valdottown) made [door](https://www.val.town/x/valdottown/door) for Val Town office guests to open the door through their phone, like [this](https://www.val.town/x/valdottown/door/pull/ef854848-34b0-11f0-9887-9e149126039e)!- [**Joey Hiller**](https://www.val.town/u/jhiller) made [ValTown-Package-Tracker](https://www.val.town/x/jhiller/ValTown-Package-Tracker) to track a package of sensors he was sending from Oakland to us in Downtown Brooklyn!- [**dinavinter**](https://www.val.town/u/dinavinter) made [slack](https://www.val.town/x/dinavinter/slack), a Slack bot that uses OpenAI to generate responses.- [**prashamtrivedi**](https://www.val.town/u/prashamtrivedi) made [hn-remote-ts-genai-jobs](https://www.val.town/x/prashamtrivedi/hn-remote-ts-genai-jobs), to track Hacker News' Who's Hiring filter for remote TypeScript + GenAI-related jobs.- [**dcm31**](https://www.val.town/u/dcm31) made [rotrank](https://www.val.town/x/dcm31/rotrank), an ELO ranking system for popular Italian Brainrot characters.
* Legal AI Document Analysis (Single Val Version with PDF Upload & Dashboard Style) * Ingests documents (URL, Text, PDF Upload), takes a user-defined legal task query, * and uses a Legal AI Agent (via OpenAI) to analyze the content. * The Legal AI Agent outputs a standardized JSON structure. * Uses 'npm:pdf.js-extract' for direct PDF text extraction within the Val.// --- Main Request Handler (Server Code) ---export default async function(req: Request) { const { OpenAI } = await import("https://esm.town/v/std/openai"); // Zod is imported globally via import statement at the top of the script const { fetch } = await import("https://esm.town/v/std/fetch"); // Using std/fetch } // --- Helper Function: Call OpenAI API --- async function callOpenAI( openai: OpenAI, systemPrompt: string, userMessage: string, log.push({ agent, type: "step", message: CONFIG.statusMessages.aiAnalysisInProgress(model) }); try { const response = await openai.chat.completions.create({ messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userMessage }], temperature: 0.2, // REFACTOR: Slightly lower for more precision message: `AI response was not valid JSON. Raw: ${content.substring(0, 250)}...`, }); console.error("OpenAI JSON Parse Error:", parseError, "Raw Content:", content); return { error: "AI_JSON_PARSE_ERROR", } } catch (error) { console.error(`OpenAI API call failed for model ${model}. Error:`, error); let errorMessage = `Error communicating with AI model (${model}).`; if (error.message) { errorMessage += ` Details: ${error.message}`; } }, ): Promise<{ finalResult?: LegalAIResponse | object; log: LogEntry[] }> { const openai = new OpenAI(); log.push({ agent: "System", type: "step", message: "Legal AI analysis workflow initiated." }); .replace("%%AI_MODEL_USED%%", input.aiModel); const aiResponseOrError = await callOpenAI(openai, finalSystemPrompt, truncatedText, input.aiModel); if (typeof aiResponseOrError === "object" && (aiResponseOrError as any).error) { // Error already logged by callOpenAI log.push({ agent: "System", type: "final", message: "Workflow finished with AI processing errors." }); return { finalResult: aiResponseOrError, log }; } // At this point, Zod validation passed in callOpenAI, so it's LegalAIResponse const aiResponse = aiResponseOrError as LegalAIResponse;
import { Hono } from "npm:hono@3";import { cors } from "npm:hono/cors";import { createOpenAI } from "npm:@ai-sdk/openai";import { createAnthropic } from "npm:@ai-sdk/anthropic@0.0.48";import { google, createGoogleGenerativeAI } from 'npm:@ai-sdk/google';});const openai = createOpenAI({ // apiKey = Deno.env.get("OPENAI_API_KEY"); apiKey: Deno.env.get("OPENAI_API_KEY_COVERSHEET")});const groq = createOpenAI({ baseURL: 'https://api.groq.com/openai/v1', apiKey: Deno.env.get("GROQ_API_KEY"),});const perplexity = createOpenAI({ apiKey: Deno.env.get("PERPLEXITY_API_KEY") ?? '', baseURL: 'https://api.perplexity.ai/', this.memories = options.memories || []; this.messages = options.messages || []; this.defaultProvider = options.provider || 'openai'; this.defaultModel = options.model; this.defaultMaxTokens = options.maxTokens; let result; switch (provider) { case 'openai': result = await this.generateOpenAIResponse({ model, prompt, maxTokens, temperature, streaming, schema, system, messages, tools, ...additionalSettings }); break; case 'anthropic': } async generateOpenAIResponse({ model, prompt, maxTokens, temperature, streaming, schema, system, messages, tools, embed, value, dimensions, user, ...additionalSettings }) { const modelId = model || 'gpt-3.5-turbo'; if (embed) { let result = await this.generateOpenAIEmbedding({ model, value, dimensions, user }); // console.log('embed!', result) return result const options = { model: openai(modelId), system, temperature, } async generateOpenAIEmbedding({ model, value, dimensions, user }) { const modelId = model || 'text-embedding-3-large'; const options = { model: openai.embedding(modelId, { dimensions, user,app.get('/generate', async (c) => { const provider = c.req.query('provider') || 'openai'; const model = c.req.query('model'); const prompt = c.req.query('prompt'); console.log("post/generate", { mode: 'post/generate', prompt, provider, model }); const response = await modelProvider.gen({ provider: provider || 'openai', model, prompt,
import { type Context, Hono } from "https://esm.sh/hono@3.11.7";import { blob } from "https://esm.town/v/std/blob";import { OpenAI } from "https://esm.town/v/std/openai";import { sqlite } from "https://esm.town/v/stevekrouse/sqlite";import Groq from "npm:groq-sdk";const app = new Hono();const openai = new OpenAI();// Get all voice notes (for admin/dashboard)async function transcribeAudio(voiceNoteId: string, audioBuffer: ArrayBuffer) { try { // Convert ArrayBuffer to File for OpenAI const audioFile = new File([audioBuffer], "audio.webm", { type: "audio/webm" });
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