All files / services/ai claude.service.ts

100% Statements 96/96
100% Branches 74/74
100% Functions 11/11
100% Lines 96/96

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525                                                                                                                                                                              4x             4x                                 53x 1x   52x                             53x 53x 53x 53x                           50x                             44x 7x 7x             7x 2x       5x 2x       3x 1x       2x 1x         1x         37x           14x 14x   14x       14x           14x                       7x             14x   14x           14x     7x         7x       7x   7x                   4x 4x   4x                         2x   4x     2x     2x 2x             4x 4x   4x                         3x       4x   4x 4x 4x                       1x           1x       2x     2x 2x                             8x 8x             7x 8x 8x 8x             1x           1x                         7x 7x           6x               13x 13x   13x                         12x         13x         13x   13x 13x       13x 13x               2x           2x       3x     3x 3x                         61x 61x   61x     61x 7x     7x       54x 1x     1x           53x 53x           53x             3x    
import { extractJSON } from "./claude-json";
import { MockAIService } from "./mock-ai.service";
import type {
	DraftPromptParams,
	MetaPromptParams,
	RewritePromptParams,
	TopicSuggestionPromptParams,
} from "./prompts";
import {
	buildDraftPrompt,
	buildMetaPrompt,
	buildRewritePrompt,
	buildTopicSuggestionPrompt,
} from "./prompts";
 
/**
 * Response types for AI service methods
 */
export interface GenerateDraftResponse {
	content: string; // Markdown content
}
 
export interface RewriteSectionResponse {
	revisedContent: string; // Markdown content
}
 
export interface GenerateMetaResponse {
	title: string;
	meta_description: string;
	suggested_slug: string;
}
 
export interface TopicSuggestion {
	title: string;
	blog_type: "general" | "project_spotlight" | "hybrid";
	primary_keyword: string;
	secondary_keywords: string[];
	outline: string;
	seo_value: string;
	pro_angle?: string;
}
 
export interface SuggestTopicsResponse {
	suggestions: TopicSuggestion[];
}
 
/**
 * Claude API response structure
 */
interface ClaudeAPIResponse {
	content: Array<{ type: string; text: string }>;
	[key: string]: unknown;
}
 
/**
 * AI Service interface
 */
export interface AIService {
	generateDraft(params: DraftPromptParams): Promise<GenerateDraftResponse>;
	rewriteSection(params: RewritePromptParams): Promise<RewriteSectionResponse>;
	generateMeta(params: MetaPromptParams): Promise<GenerateMetaResponse>;
	suggestTopics(
		params: TopicSuggestionPromptParams,
	): Promise<SuggestTopicsResponse>;
	/** General-purpose JSON generation — sends a prompt, parses JSON response */
	generateJSON<T>(
		prompt: string,
		options?: {
			model?: "opus" | "haiku";
			maxTokens?: number;
			temperature?: number;
		},
	): Promise<T>;
	/** Generate free-form text content from a prompt */
	generateText(
		prompt: string,
		options?: {
			model?: "opus" | "haiku";
			maxTokens?: number;
			temperature?: number;
		},
	): Promise<string>;
}
 
/**
 * Claude API configuration
 */
const CLAUDE_MODELS = {
	// Use Opus 4.5 for content generation (drafts, rewrites) - latest model with best quality
	OPUS: "claude-opus-4-5-20251101",
	// Use Haiku 4.5 for faster, cheaper operations (meta, suggestions)
	HAIKU: "claude-haiku-4-5-20251001",
} as const;
 
const MAX_TOKENS = {
	DRAFT: 4096, // Full blog content
	REWRITE: 2048, // Section rewrite
	META: 512, // Short metadata
	TOPICS: 2048, // Topic suggestions list
} as const;
 
/**
 * Build the Claude API endpoint URL.
 * If AI Gateway is configured (both CLOUDFLARE_ACCOUNT_ID and AI_GATEWAY_SLUG set),
 * routes through Cloudflare AI Gateway for caching, analytics, and rate limiting.
 * Otherwise falls back to direct Anthropic API.
 */
function getClaudeApiUrl(env?: {
	CLOUDFLARE_ACCOUNT_ID?: string;
	AI_GATEWAY_SLUG?: string;
}): string {
	if (env?.CLOUDFLARE_ACCOUNT_ID && env?.AI_GATEWAY_SLUG) {
		return `https://gateway.ai.cloudflare.com/v1/${env.CLOUDFLARE_ACCOUNT_ID}/${env.AI_GATEWAY_SLUG}/anthropic/v1/messages`;
	}
	return "https://api.anthropic.com/v1/messages";
}
 
/**
 * Real Claude API implementation using direct fetch for Cloudflare Workers compatibility.
 * Supports optional Cloudflare AI Gateway for caching, analytics, and rate limiting.
 */
class ClaudeAIService implements AIService {
	private apiKey: string;
	private apiUrl: string;
 
	constructor(
		apiKey: string,
		env?: { CLOUDFLARE_ACCOUNT_ID?: string; AI_GATEWAY_SLUG?: string },
	) {
		this.apiKey = apiKey;
		this.apiUrl = getClaudeApiUrl(env);
		const usingGateway = this.apiUrl.includes("gateway.ai.cloudflare.com");
		console.log(
			`[ClaudeAIService] Service initialized (AI Gateway: ${usingGateway ? "enabled" : "disabled"})`,
		);
	}
 
	/**
	 * Call Claude API using fetch for better Cloudflare Workers compatibility
	 */
	private async callClaudeAPI(
		model: string,
		maxTokens: number,
		temperature: number,
		messages: Array<{ role: string; content: string }>,
	): Promise<ClaudeAPIResponse> {
		const response = await fetch(this.apiUrl, {
			method: "POST",
			headers: {
				"Content-Type": "application/json",
				"x-api-key": this.apiKey,
				"anthropic-version": "2023-06-01",
			},
			body: JSON.stringify({
				model,
				max_tokens: maxTokens,
				temperature,
				messages,
			}),
		});
 
		if (!response.ok) {
			const errorBody = await response.text();
			console.error("[ClaudeAPI] API call failed:", {
				status: response.status,
				statusText: response.statusText,
				body: errorBody,
			});
 
			// Provide specific error messages based on status code
			if (response.status === 401 || response.status === 403) {
				throw new Error(
					"AI service authentication failed. Please verify CLAUDE_API_KEY is correct.",
				);
			}
			if (response.status === 429) {
				throw new Error(
					"AI service rate limit exceeded. Please try again in a few minutes.",
				);
			}
			if (response.status === 503 || response.status === 502) {
				throw new Error(
					"AI service temporarily unavailable. Please try again later.",
				);
			}
			if (response.status === 400) {
				throw new Error(
					`Invalid request to AI service: ${errorBody.substring(0, 100)}`,
				);
			}
 
			throw new Error(
				`Claude API error: ${response.status} ${response.statusText}`,
			);
		}
 
		return response.json();
	}
 
	async generateDraft(
		params: DraftPromptParams,
	): Promise<GenerateDraftResponse> {
		try {
			const prompt = buildDraftPrompt(params);
 
			console.log(
				"[generateDraft] Starting AI draft generation with model:",
				CLAUDE_MODELS.OPUS,
			);
			console.log(
				"[generateDraft] Prompt length:",
				prompt.length,
				"characters",
			);
 
			const response = await this.callClaudeAPI(
				CLAUDE_MODELS.OPUS,
				MAX_TOKENS.DRAFT,
				0.7, // Some creativity for engaging content
				[
					{
						role: "user",
						content: prompt,
					},
				],
			);
 
			console.log(
				"[generateDraft] AI response received, content blocks:",
				response.content?.length,
			);
 
			// Extract text content from response
			const content =
				response.content?.[0]?.type === "text" ? response.content[0].text : "";
 
			console.log(
				"[generateDraft] Extracted content length:",
				content.length,
				"characters",
			);
 
			return { content };
		} catch (err) {
			// Enhanced error logging with more details
			const errorDetails: { name: string; message: string } = {
				name: err instanceof Error ? err.name : "Unknown",
				message: err instanceof Error ? err.message : String(err),
			};
 
			console.error(
				"[generateDraft] AI draft generation failed:",
				errorDetails,
			);
			console.error("[generateDraft] Full error:", err);
 
			throw new Error(
				"AI service error: " +
					(err instanceof Error ? err.message : "Unknown error"),
			);
		}
	}
 
	async rewriteSection(
		params: RewritePromptParams,
	): Promise<RewriteSectionResponse> {
		try {
			const prompt = buildRewritePrompt(params);
 
			const response = await this.callClaudeAPI(
				CLAUDE_MODELS.OPUS,
				MAX_TOKENS.REWRITE,
				0.5, // Moderate creativity, stay closer to original
				[
					{
						role: "user",
						content: prompt,
					},
				],
			);
 
			const revisedContent =
				response.content?.[0]?.type === "text" ? response.content[0].text : "";
 
			return { revisedContent };
		} catch (err) {
			const safeError =
				err instanceof Error
					? { message: err.message, name: err.name }
					: { error: "Unknown error" };
			console.error("AI section rewrite failed:", safeError);
			throw new Error(
				`AI service error: ${err instanceof Error ? err.message : "Unknown"}`,
			);
		}
	}
 
	async generateMeta(params: MetaPromptParams): Promise<GenerateMetaResponse> {
		try {
			const prompt = buildMetaPrompt(params);
 
			const response = await this.callClaudeAPI(
				CLAUDE_MODELS.HAIKU, // Use faster model for structured output
				MAX_TOKENS.META,
				0, // Deterministic for consistent metadata
				[
					{
						role: "user",
						content: prompt,
					},
				],
			);
 
			const jsonText =
				response.content?.[0]?.type === "text"
					? response.content[0].text
					: "{}";
 
			try {
				// Extract JSON from potential markdown wrapper and parse
				const cleanedJSON = extractJSON(jsonText);
				const parsed = JSON.parse(cleanedJSON) as GenerateMetaResponse;
				return {
					title: parsed.title || "",
					meta_description: parsed.meta_description || "",
					suggested_slug: parsed.suggested_slug || "",
				};
			} catch (parseError) {
				/* v8 ignore start -- defensive: JSON.parse always throws Error subclass */
				const errMsg =
					parseError instanceof Error ? parseError.message : String(parseError);
				const errName =
					parseError instanceof Error ? parseError.name : "Unknown";
				/* v8 ignore stop */
				console.error(
					"Failed to parse meta generation response:",
					{ message: errMsg, name: errName },
					"Response preview:",
					jsonText.substring(0, 200),
				);
				throw new Error("Invalid JSON response from AI service");
			}
		} catch (err) {
			const safeError =
				err instanceof Error
					? { message: err.message, name: err.name }
					: { error: "Unknown error" };
			console.error("AI meta generation failed:", safeError);
			throw new Error(
				`AI service error: ${err instanceof Error ? err.message : "Unknown"}`,
			);
		}
	}
 
	async generateJSON<T>(
		prompt: string,
		options?: {
			model?: "opus" | "haiku";
			maxTokens?: number;
			temperature?: number;
		},
	): Promise<T> {
		const model =
			options?.model === "opus" ? CLAUDE_MODELS.OPUS : CLAUDE_MODELS.HAIKU;
		const response = await this.callClaudeAPI(
			model,
			options?.maxTokens ?? 2048,
			options?.temperature ?? 0,
			[{ role: "user", content: prompt }],
		);
		const text =
			response.content?.[0]?.type === "text" ? response.content[0].text : "{}";
		const cleaned = extractJSON(text);
		try {
			return JSON.parse(cleaned) as T;
		} catch (parseError) {
			/* v8 ignore start -- defensive: JSON.parse always throws Error subclass */
			const errMsg =
				parseError instanceof Error ? parseError.message : String(parseError);
			const errName = parseError instanceof Error ? parseError.name : "Unknown";
			/* v8 ignore stop */
			console.error(
				"Failed to parse JSON response from AI service:",
				{ message: errMsg, name: errName },
				"Response preview:",
				text.substring(0, 200),
			);
			throw new Error("Invalid JSON response from AI service");
		}
	}
 
	async generateText(
		prompt: string,
		options?: {
			model?: "opus" | "haiku";
			maxTokens?: number;
			temperature?: number;
		},
	): Promise<string> {
		const model =
			options?.model === "opus" ? CLAUDE_MODELS.OPUS : CLAUDE_MODELS.HAIKU;
		const response = await this.callClaudeAPI(
			model,
			options?.maxTokens ?? 4096,
			options?.temperature ?? 0.7,
			[{ role: "user", content: prompt }],
		);
		return response.content?.[0]?.type === "text"
			? response.content[0].text
			: "";
	}
 
	async suggestTopics(
		params: TopicSuggestionPromptParams,
	): Promise<SuggestTopicsResponse> {
		try {
			const prompt = buildTopicSuggestionPrompt(params);
 
			const response = await this.callClaudeAPI(
				CLAUDE_MODELS.HAIKU, // Use faster model for suggestions
				MAX_TOKENS.TOPICS,
				0.8, // Higher creativity for diverse topic ideas
				[
					{
						role: "user",
						content: prompt,
					},
				],
			);
 
			const jsonText =
				response.content?.[0]?.type === "text"
					? response.content[0].text
					: "[]";
 
			// Debug logging - log first 500 chars of raw response
			console.log(
				"[suggestTopics] Raw Claude response (first 500 chars):",
				jsonText.substring(0, 500),
			);
 
			try {
				// Extract JSON from potential markdown wrapper and parse
				const cleanedJSON = extractJSON(jsonText);
				console.log(
					"[suggestTopics] Cleaned JSON (first 500 chars):",
					cleanedJSON.substring(0, 500),
				);
				const suggestions = JSON.parse(cleanedJSON) as TopicSuggestion[];
				return { suggestions };
			} catch (parseError) {
				/* v8 ignore start -- defensive: JSON.parse always throws Error subclass */
				const errMsg =
					parseError instanceof Error ? parseError.message : String(parseError);
				const errName =
					parseError instanceof Error ? parseError.name : "Unknown";
				/* v8 ignore stop */
				console.error(
					"Failed to parse topic suggestions response:",
					{ message: errMsg, name: errName },
					"Response preview:",
					jsonText.substring(0, 200),
				);
				throw new Error("Invalid JSON response from AI service");
			}
		} catch (err) {
			const safeError =
				err instanceof Error
					? { message: err.message, name: err.name }
					: { error: "Unknown error" };
			console.error("AI topic suggestion failed:", safeError);
			throw new Error(
				`AI service error: ${err instanceof Error ? err.message : "Unknown"}`,
			);
		}
	}
}
 
/**
 * Factory function to create appropriate AI service based on environment
 * Returns mock service ONLY if AI features are explicitly disabled
 * Throws error if AI is enabled but API key is missing (fail fast)
 */
export function createAIService(env: CloudflareBindings): AIService {
	const aiEnabled = env.ENABLE_AI_FEATURES === "true";
	const hasApiKey = !!env.CLAUDE_API_KEY;
 
	console.log("[createAIService] AI enabled:", aiEnabled);
 
	// AI explicitly disabled - use mock service
	if (!aiEnabled) {
		console.warn(
			"[createAIService] AI features explicitly disabled, using mock service",
		);
		return new MockAIService();
	}
 
	// AI enabled but no API key - this is a configuration error, fail fast
	if (!hasApiKey) {
		console.error(
			"[createAIService] CLAUDE_API_KEY not configured but AI is enabled",
		);
		throw new Error(
			"AI features enabled but CLAUDE_API_KEY not configured. Please set CLAUDE_API_KEY environment variable or disable AI features.",
		);
	}
 
	// AI enabled with API key - use real service (guaranteed to exist after check above)
	console.log("[createAIService] Creating Claude AI service");
	const apiKey = env.CLAUDE_API_KEY;
	/* v8 ignore start -- defensive guard; apiKey validated above */
	if (!apiKey) {
		throw new Error("CLAUDE_API_KEY is required but not found");
	}
	/* v8 ignore stop */
	return new ClaudeAIService(apiKey, env);
}
 
/**
 * Check if AI features are enabled in the environment
 */
export function isAIEnabled(env: CloudflareBindings): boolean {
	return env.ENABLE_AI_FEATURES === "true" && !!env.CLAUDE_API_KEY;
}