Search

3,343 results found for openai (1835ms)

Code
3,248

// Lou Fantasy Baseball OpenAI AI Analysis Client
// Robust OpenAI API integration for fantasy baseball performance analysis
// Val.town Compatible TypeScript Implementation
// ============================================================================
// OPENAI CLIENT INTERFACES
// ============================================================================
/**
* AI Performance Analysis Response Interface
* Structured output from OpenAI analysis of fantasy baseball performance
*/
export interface AIPerformanceAnalysis {
/**
* OpenAI API Configuration Interface
*/
export interface OpenAIConfig {
apiKey: string;
model: string;
/**
* OpenAI API Error Interface
*/
export interface OpenAIError {
type: 'RATE_LIMIT' | 'API_ERROR' | 'TIMEOUT' | 'PARSE_ERROR' | 'AUTH_ERROR' | 'UNKNOWN';
message: string;
// ============================================================================
// OPENAI CLIENT IMPLEMENTATION
// ============================================================================
/**
* Lou OpenAI Client - Robust AI Analysis for Fantasy Baseball
*
* Features:
* - Val.town optimized implementation
*/
export class LouOpenAIClient {
private config: OpenAIConfig;
private requestQueue: Array<() => Promise<any>> = [];
private isProcessingQueue: boolean = false;
private readonly MIN_REQUEST_INTERVAL = 1000; // 1 second between requests
constructor(config?: Partial<OpenAIConfig>) {
this.config = {
apiKey: config?.apiKey || process.env.OPENAI_API_KEY || '',
model: config?.model || process.env.OPENAI_MODEL || 'o4-mini',
maxTokens: config?.maxTokens || 2000,
temperature: config?.temperature || 0.7,
if (!this.config.apiKey) {
console.error('❌ OpenAI API key not provided. Set OPENAI_API_KEY environment variable.');
}
console.log(`🤖 Lou OpenAI Client initialized with model: ${this.config.model}`);
}
// Log the request
aiLogger.logOpenAiRequest(this.config.model, prompt, this.config);
// Execute OpenAI request with retry logic
const response = await this.executeWithRetry(async () => {
return await this.makeOpenAIRequest(prompt, 'performance_analysis');
});
// Log the request
aiLogger.logOpenAiRequest(this.config.model, prompt, this.config);
// Execute OpenAI request
const response = await this.executeWithRetry(async () => {
return await this.makeOpenAIRequest(prompt, 'waiver_recommendations');
});
/**
* Execute OpenAI API request with comprehensive retry logic
*/
private async executeWithRetry<T>(operation: () => Promise<T>): Promise<T | null> {
/**
* Make OpenAI API request with proper error handling
*/
private async makeOpenAIRequest(prompt: string, requestType: string): Promise<string | null> {
const startTime = Date.now();
try {
console.log(`🤖 Making OpenAI request: ${requestType}`);
// Validate API key
if (!this.config.apiKey) {
throw new Error('OpenAI API key not configured');
}
const timeoutId = setTimeout(() => controller.abort(), this.config.requestTimeout);
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
if (!response.ok) {
const errorText = await response.text();
throw this.createOpenAIError(response.status, errorText);
}
if (!content) {
throw new Error('Empty response from OpenAI API');
}
const duration = Date.now() - startTime;
console.log(`✅ OpenAI request completed in ${duration}ms`);
// Log the response
aiLogger.logOpenAiResponse(this.config.model, content, duration, data.usage?.total_tokens)
return content;
if (error.name === 'AbortError') {
console.error(`⏰ OpenAI request timeout after ${duration}ms`);
throw this.createOpenAIError(408, 'Request timeout');
}
console.error(`❌ OpenAI request failed after ${duration}ms:`, error);
throw error;
}
/**
* Create standardized OpenAI error
*/
private createOpenAIError(statusCode: number, message: string): OpenAIError {
let type: OpenAIError['type'] = 'UNKNOWN';
if (statusCode === 401) type = 'AUTH_ERROR';
/**
* Validate OpenAI configuration
*/
public validateConfig(): { valid: boolean; errors: string[] } {
if (!this.config.apiKey) {
errors.push('OpenAI API key is required');
}
if (!this.config.model) {
errors.push('OpenAI model is required');
}
* Get current configuration (without API key)
*/
public getConfig(): Omit<OpenAIConfig, 'apiKey'> {
const { apiKey, ...configWithoutKey } = this.config;
return configWithoutKey;
/**
* Test OpenAI API connection
*/
async testConnection(): Promise<{ success: boolean; error?: string; model?: string }> {
try {
console.log('🧪 Testing OpenAI API connection...');
const response = await this.makeOpenAIRequest(
'Please respond with a simple JSON object: {"status": "connected", "message": "API test
'connection_test'
const parsed = JSON.parse(response);
if (parsed.status === 'connected') {
console.log('✅ OpenAI API connection successful');
return { success: true, model: this.config.model };
}
} catch (error) {
console.error('❌ OpenAI API connection test failed:', error);
return {
success: false,
/**
* Create a configured LouOpenAIClient instance
* @param config Optional configuration overrides
* @returns Configured OpenAI client
*/
export function createOpenAIClient(config?: Partial<OpenAIConfig>): LouOpenAIClient {
return new LouOpenAIClient(config);
}
/**
* Validate performance data before sending to OpenAI
* @param data Performance data to validate
* @returns Validation result
import { LouPerformanceAnalyzer, PerformanceAnalysisReport } from "./ai_performance_yahoo_integr
import {
LouOpenAIClient,
createOpenAIClient,
AIPerformanceAnalysis,
WaiverRecommendation
} from "./ai_performance_openai_client.ts";
import { LouTokenStorage } from "../oauth/token_storage.tsx";
import {
const performanceAnalyzer = new LouPerformanceAnalyzer();
const openaiClient = createOpenAIClient({
model: 'gpt-4o-mini', // More reliable than o4-mini
maxTokens: 1500, // Reduce tokens for speed
try {
// Run team analysis first (faster, more important)
aiAnalysis = await openaiClient.analyzeTeamPerformance({
teamStats: performanceReport.team_analysis.overall_performance,
playerStats: performanceReport.player_insights.top_performers.concat(performanceReport
const topCandidates = availableWaiverPlayers.slice(0, 6); // Limit to 6 candidates
waiverRecommendations = await openaiClient.getPickupRecommendations(
performanceReport.player_insights.underperformers.slice(0, 4), // Top 4 underperfo
topCandidates
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" },
_2 or_3) to create a fresh table.
### 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";
const client = new OpenAI();
const response = await client.responses.create({
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" },
}))
const { categorizeIssues: categorizeWithAI } = await import('./openai.ts')
return categorizeWithAI(processedIssues)
}
2. **Environment Variables** (left sidebar)
```bash
OPENAI_API_KEY=your_openai_api_key_here
```
## Customization
Edit the system prompt in `openai.ts` to change how issues are categorized.
## Output
import OpenAI from 'npm:openai'
const openai = new OpenAI({
apiKey: Deno.env.get('OPENAI_API_KEY')
})
export async function categorizeIssues(issues: any[]) {
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: `Analyze these GitHub issues and categorize them into a
const aiResponse = completion.choices[0].message.content
if (!aiResponse) throw new Error('OpenAI returned empty response')
try {
return JSON.parse(aiResponse)
} catch (error) {
console.error('Failed to parse OpenAI response:', aiResponse.substring(0, 1000) + '...')
// Try to repair truncated JSON by finding the last complete array
return JSON.parse(repairedResponse)
} catch (repairError) {
throw new Error(`Invalid JSON response from OpenAI: ${error.message}`)
}
}
import { OpenAI } from "npm:openai";
import ValTown from "npm:@valtown/sdk";
const openai = new OpenAI();
const client = new ValTown();
}
const response = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{