Search

3,360 results found for openai (1787ms)

Code
3,265

Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to cre
### OpenAI
```ts
import { 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" },
import {OpenAI} from "npm:openai"
import {ParsedResume, ResumeParserOptions, ConfidenceField, DateRange} from "../types/resume.ts"
import {generatePrompt} from "../prompts/resumePrompts.ts"
import {OpenAICompatibleResumeSchema, ParsedResumeSchema} from "../schemas/resumeSchemas.ts"
import {z} from "npm:@hono/zod-openapi"
import {zodResponseFormat} from "npm:openai/helpers/zod"
/**
* Parse resume text using OpenAI and return structured data
*
* @param resumeText The plain text of the resume to parse
}
// Initialize OpenAI client (uses API key from environment in ValTown)
const openai = new OpenAI()
// Get extraction prompt
${extractionFocus}${extractLanguages}${extractSummary}`
console.log("Calling OpenAI API for initial extraction...")
// Call OpenAI API with enhanced system prompt and structured output schema
const completion = await openai.beta.chat.completions.parse({
model: "gpt-4o",
messages: [
{role: "user", content: extractPrompt + "\n\nResume Text:\n" + resumeText}
],
response_format: zodResponseFormat(OpenAICompatibleResumeSchema, 'parsedResume')
})
if (!responseContent) {
throw new Error("Empty response from OpenAI")
}
console.error("JSON parsing error:", error)
throw new Error("Failed to parse OpenAI response as valid JSON")
}
} catch (error) {
console.error("OpenAI parsing error:", error)
// Provide specific error message based on the error type
if ((error as Error).message.includes("429")) {
throw new Error("OpenAI rate limit exceeded. Please try again later.")
} else if ((error as Error).message.includes("401") || (error as Error).message.includes("40
throw new Error("Authentication error with OpenAI API. Check your API key.")
} else {
throw new Error("Failed to parse resume with OpenAI: " + (error as Error).message)
}
}
/**
* Validate extracted data using OpenAI
*
* @param data The extracted resume data to validate
export async function validateResumeWithAI(data: ParsedResume): Promise<ParsedResume> {
try {
// Initialize OpenAI client
const openai = new OpenAI()
// Get validation prompt
Always return the complete JSON structure with your improvements.`
console.log("Calling OpenAI API for validation and standardization...")
// Call OpenAI API with enhanced validation
const completion = await openai.beta.chat.completions.parse({
model: "gpt-4o",
messages: [
{role: "user", content: validationPrompt + "\n\nResume Data:\n" + JSON.stringify(data)}
],
response_format: zodResponseFormat(OpenAICompatibleResumeSchema, 'validResume')
})
if (!responseContent) {
throw new Error("Empty validation response from OpenAI")
}
}
} catch (error) {
console.error("OpenAI validation error:", error)
console.warn("Using original data due to validation API error")
// Return original data if validation API call fails
/**
* Helper function to check if OpenAI extraction result is valid
* and retry if necessary with a different prompt strategy
*
console.log("Initial extraction had issues, attempting retry with different strategy...")
// Initialize OpenAI client
const openai = new OpenAI()
// Create a simplified extraction prompt focused on missing data
// Call OpenAI API with retry strategy
const completion = await openai.beta.chat.completions.parse({
model: "gpt-4o",
messages: [
Please provide a complete and corrected JSON response following the exact same schema.` }
],
response_format: zodResponseFormat(OpenAICompatibleResumeSchema, 'retriedResume')
})
/**
* Convert simplified OpenAI schema format to full ParsedResume format with confidence fields
* @param simplified Simplified resume data returned from OpenAI
* @returns Fully structured resume data with confidence fields
*/
Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to cre
### OpenAI
```ts
import { 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 cre
### OpenAI
```ts
import { 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" },
} from '../types/resume.ts';
import { generatePrompt } from '../prompts/resumePrompts.ts';
import { parseResumeWithAI, validateResumeWithAI, retryExtractionIfNeeded } from './openai.ts';
/**
const standardizationEnabled = options?.standardizationEnabled !== false; // Default to true
// Step 1: Initial extraction with OpenAI
console.log('Step 1: Performing initial extraction with OpenAI');
let extractedData = await parseResumeWithAI(resumeText, options);
export function validateAndStandardize(data: ParsedResume): ParsedResume {
// This function is now deprecated in favor of the validateResumeWithAI function
// which uses OpenAI to validate and standardize the data
return data;
}
import { AgentContext, AgentInput, AgentOutput } from "https://esm.town/v/salon/mandate/interfac
import { fetch } from "https://esm.town/v/std/fetch";
import { OpenAI } from "https://esm.town/v/std/openai";
// If Deno.env is used, ensure it's for Val Town secrets if possible or clearly noted.
// For direct Deno.env.get('OPENAI_API_KEY'), it relies on the Val Town environment variable bei
// The std/openai library usually handles API key abstraction using user's Val Town secrets.
// Your provided summarizerAgent
}
const openai = new OpenAI(); // Using OpenAI client as per your example
log("INFO", "SummarizerAgent", "Generating summary with OpenAI...");
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini", // Explicitly setting a model
messages: [
if (summary === "Could not generate summary.") {
log("WARN", "SummarizerAgent", "OpenAI did not return a valid summary content.");
}
// Your provided combinerAgent (not directly used in the 12-step orchestrator, but kept for refe
export async function combinerAgent(
// ... (combinerAgent code as you provided, also updating its OpenAI call) ...
input: AgentInput<{
summary?: string;
}
const openai = new OpenAI(); // Using OpenAI client as per your example
log("INFO", "CombinerAgent", "Combining text with OpenAI...");
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini", // Explicitly setting a model
messages: [
const combined = completion.choices[0]?.message?.content?.trim() ?? "Could not combine infor
if (combined === "Could not combine information.")
log("WARN", "CombinerAgent", "OpenAI did not return valid combined content.");
log("SUCCESS", "CombinerAgent", "Combined successfully");
return { mandateId, correlationId: taskId, payload: { combined } };
const { userQuery } = input.payload;
log("INFO", "ConfigurationAgent", `Processing query: ${userQuery}`);
const openai = new OpenAI();
const systemPrompt =
try {
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "system", content: systemPrompt }, { role: "user", content: userQuery }
const { log } = context;
const { articles, topic, keywords } = input.payload;
const openai = new OpenAI();
let relevantArticles: FetchedArticle[] = [];
log("INFO", "RelevanceAssessmentAgent", `Assessing relevance for ${articles.length} articles o
let assessment = { isRelevant: false, rationale: "LLM assessment failed or unclear." };
try {
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "system", content: "You are a relevance assessor. Output JSON." }, {
): Promise<AgentOutput<{ articlesWithSentiment: FetchedArticle[] }>> {
const { log } = context;
const openai = new OpenAI();
let articlesWithSentiment: FetchedArticle[] = [];
if (!input.payload.articles)
let sentimentScore: FetchedArticle["sentimentScore"] = 0.0;
try {
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "system", content: "You are a sentiment analysis expert. Output JSON.
): Promise<AgentOutput<{ articlesWithThemes: FetchedArticle[] }>> {
const { log } = context;
const openai = new OpenAI();
let articlesWithThemes: FetchedArticle[] = [];
log(
let themeResult: { themes: string[]; entities: FetchedArticle["entities"] } = { themes: [],
try {
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "system", content: "You are a thematic/NER expert. Output JSON." }, {
const { log } = context;
const { articlesWithThemes, topic, historicalContextSummary } = input.payload;
const openai = new OpenAI();
log(
"INFO",
let trendReport: any = { dominantSentiment: "N/A", keyThemes: [], emergingPatterns: "Not analy
try {
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "system", content: "Trend analysis expert. Output JSON." }, {
let anomalyReport: any = { anomaliesFound: false, anomalyDetails: [] };
try {
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "system", content: "Anomaly detection expert. Output JSON." }, {
const { log } = context;
const { trendReport, anomalyReport, config, articlesCount } = input.payload;
const openai = new OpenAI();
log("INFO", "InsightGenerationAgent", `Generating insights for topic: ${config.topic}`);
const contextSummary =
let insights: string[] = ["No specific insights generated."];
try {
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "system", content: "Strategic analyst providing concise insights." }, {
log("INFO", "ReportCompilationAgent", `Compiling report for topic: ${config.topic}`); // Direc
const openai = new OpenAI(); // Ensure API key is configured via environment variables or clie
// The agent code used 'relevantArticles'. If 'articlesWithThemes' is the correct data source
let finalReport = "Report generation failed.";
try {
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [
const { log } = context;
const { anomalyReport, insights, config } = input.payload;
const openai = new OpenAI();
let criticalInfo = "";
if (anomalyReport?.anomaliesFound && anomalyReport.anomalyDetails.length > 0) {
let alertMessage: string | undefined = undefined;
try {
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "system", content: "Alert generation specialist." }, { role: "user", co
Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to cre
### OpenAI
```ts
import { 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" },
Get/Bizdev/Main.ts
11 matches
import { validator } from "https://esm.sh/hono@4.3.7/validator";
// Using @valtown/sqlite
import { OpenAI } from "https://esm.town/v/std/openai?v=1";
import { Batch, sqlite, Statement } from "https://esm.town/v/std/sqlite?v=4";
async function draftColdEmail(
openai: OpenAI,
businessName: string | undefined,
websiteUrl: string,
try {
const chatCompletion = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: prompt }],
const responseText = chatCompletion.choices[0]?.message?.content?.trim();
if (!responseText) {
eLeadStatus(leadId, "error_drafting_empty_response", {}, "OpenAI returned empty response");
return null;
}
} catch (error) {
console.error(`Error drafting email for ${emailAddress} (lead ${leadId}):`, error);
await updateLeadStatus(leadId, "error_drafting", {}, `OpenAI API error: ${error.message}`);
return null;
}
async function processJob(jobId: string, searchQuery: string) {
await updateJobStatus(jobId, "processing_search");
const openaiApiKey = Deno.env.get("openai");
if (!openaiApiKey) {
console.error("OpenAI API key secret 'openai' is not set.");
await updateJobStatus(jobId, "failed_config", "OpenAI API key not configured.");
return;
}
const openai = new OpenAI({ apiKey: openaiApiKey });
const websites = await searchWebsites(searchQuery, jobId);
const emailAddress = await extractEmailsFromWebsite(site.url, leadId);
if (emailAddress) {
await draftColdEmail(openai, truncatedBusinessName, site.url, emailAddress, searchQuery, l
}
}
Note: When changing a SQLite table's schema, change the table's name (e.g., add _2 or _3) to cre
### OpenAI
```ts
import { 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" },
},
{
"title": "An Introduction to OpenAI fine-tuning",
"slug": "an-introduction-to-openai-fine-tuning",
"link": "/blog/an-introduction-to-openai-fine-tuning",
"description": "How to customize OpenAI to your liking",
"pubDate": "Fri, 25 Aug 2023 00:00:00 GMT",
"author": "Steve Krouse",
"slug": "val-town-newsletter-16",
"link": "/blog/val-town-newsletter-16",
"description": "Our seed round, growing team, Codeium completions, @std/openai, and more",
"pubDate": "Mon, 22 Apr 2024 00:00:00 GMT",
"author": "Steve Krouse",