@contentgrowth/llm-service 1.2.1 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -155,6 +155,44 @@ declare class OpenAIProvider extends BaseLLMProvider {
155
155
  getDeepResearchStatus(operationId: any): Promise<void>;
156
156
  }
157
157
 
158
+ declare class AnthropicProvider extends BaseLLMProvider {
159
+ models: any;
160
+ defaultModel: any;
161
+ chat(userMessage: any, systemPrompt?: string, options?: {}): Promise<{
162
+ text: any;
163
+ }>;
164
+ chatCompletion(messages: any, systemPrompt: any, tools?: any, options?: {}): Promise<{
165
+ content: any;
166
+ tool_calls: any;
167
+ finishReason: string;
168
+ _rawFinishReason: any;
169
+ _responseFormat: any;
170
+ usage: {
171
+ prompt_tokens: any;
172
+ completion_tokens: any;
173
+ total_tokens: any;
174
+ };
175
+ model: any;
176
+ }>;
177
+ _chatCompletionWithModel(messages: any, systemPrompt: any, tools: any, modelName: any, maxTokens: any, temperature: any, options?: {}): Promise<{
178
+ content: any;
179
+ tool_calls: any;
180
+ finishReason: string;
181
+ _rawFinishReason: any;
182
+ _responseFormat: any;
183
+ usage: {
184
+ prompt_tokens: any;
185
+ completion_tokens: any;
186
+ total_tokens: any;
187
+ };
188
+ model: any;
189
+ }>;
190
+ _getModelForTier(tier: any): any;
191
+ _shouldAutoParse(options: any): boolean;
192
+ _safeJsonParse(text: any): any;
193
+ normalizeFinishReason(providerReason: any): string;
194
+ }
195
+
158
196
  /**
159
197
  * Create a Hono handler for speech transcription.
160
198
  *
@@ -411,6 +449,18 @@ declare namespace MODEL_CONFIGS {
411
449
  let image_1: string;
412
450
  export { image_1 as image };
413
451
  }
452
+ namespace anthropic {
453
+ let _default_3: string;
454
+ export { _default_3 as default };
455
+ let edge_3: string;
456
+ export { edge_3 as edge };
457
+ let fast_3: string;
458
+ export { fast_3 as fast };
459
+ let cost_3: string;
460
+ export { cost_3 as cost };
461
+ let free_3: string;
462
+ export { free_3 as free };
463
+ }
414
464
  }
415
465
  declare class ConfigManager {
416
466
  static _provider: DefaultConfigProvider;
@@ -667,4 +717,4 @@ declare class TranscriptionServiceException extends Error {
667
717
  statusCode: number;
668
718
  }
669
719
 
670
- export { BaseConfigProvider$1 as BaseConfigProvider, ConfigManager, DefaultConfigProvider, FINISH_REASONS, GoogleProvider as GeminiProvider, GoogleProvider, LLMService, LLMServiceException, MODEL_CONFIGS, OpenAIProvider, TranscriptionService, TranscriptionServiceException, GoogleProvider as VertexProvider, createSpeechHandler, extractJsonFromResponse, extractTextAndJson, handleApiError, sanitizeError };
720
+ export { AnthropicProvider, BaseConfigProvider$1 as BaseConfigProvider, ConfigManager, DefaultConfigProvider, FINISH_REASONS, GoogleProvider as GeminiProvider, GoogleProvider, LLMService, LLMServiceException, MODEL_CONFIGS, OpenAIProvider, TranscriptionService, TranscriptionServiceException, GoogleProvider as VertexProvider, createSpeechHandler, extractJsonFromResponse, extractTextAndJson, handleApiError, sanitizeError };
package/dist/index.d.ts CHANGED
@@ -155,6 +155,44 @@ declare class OpenAIProvider extends BaseLLMProvider {
155
155
  getDeepResearchStatus(operationId: any): Promise<void>;
156
156
  }
157
157
 
158
+ declare class AnthropicProvider extends BaseLLMProvider {
159
+ models: any;
160
+ defaultModel: any;
161
+ chat(userMessage: any, systemPrompt?: string, options?: {}): Promise<{
162
+ text: any;
163
+ }>;
164
+ chatCompletion(messages: any, systemPrompt: any, tools?: any, options?: {}): Promise<{
165
+ content: any;
166
+ tool_calls: any;
167
+ finishReason: string;
168
+ _rawFinishReason: any;
169
+ _responseFormat: any;
170
+ usage: {
171
+ prompt_tokens: any;
172
+ completion_tokens: any;
173
+ total_tokens: any;
174
+ };
175
+ model: any;
176
+ }>;
177
+ _chatCompletionWithModel(messages: any, systemPrompt: any, tools: any, modelName: any, maxTokens: any, temperature: any, options?: {}): Promise<{
178
+ content: any;
179
+ tool_calls: any;
180
+ finishReason: string;
181
+ _rawFinishReason: any;
182
+ _responseFormat: any;
183
+ usage: {
184
+ prompt_tokens: any;
185
+ completion_tokens: any;
186
+ total_tokens: any;
187
+ };
188
+ model: any;
189
+ }>;
190
+ _getModelForTier(tier: any): any;
191
+ _shouldAutoParse(options: any): boolean;
192
+ _safeJsonParse(text: any): any;
193
+ normalizeFinishReason(providerReason: any): string;
194
+ }
195
+
158
196
  /**
159
197
  * Create a Hono handler for speech transcription.
160
198
  *
@@ -411,6 +449,18 @@ declare namespace MODEL_CONFIGS {
411
449
  let image_1: string;
412
450
  export { image_1 as image };
413
451
  }
452
+ namespace anthropic {
453
+ let _default_3: string;
454
+ export { _default_3 as default };
455
+ let edge_3: string;
456
+ export { edge_3 as edge };
457
+ let fast_3: string;
458
+ export { fast_3 as fast };
459
+ let cost_3: string;
460
+ export { cost_3 as cost };
461
+ let free_3: string;
462
+ export { free_3 as free };
463
+ }
414
464
  }
415
465
  declare class ConfigManager {
416
466
  static _provider: DefaultConfigProvider;
@@ -667,4 +717,4 @@ declare class TranscriptionServiceException extends Error {
667
717
  statusCode: number;
668
718
  }
669
719
 
670
- export { BaseConfigProvider$1 as BaseConfigProvider, ConfigManager, DefaultConfigProvider, FINISH_REASONS, GoogleProvider as GeminiProvider, GoogleProvider, LLMService, LLMServiceException, MODEL_CONFIGS, OpenAIProvider, TranscriptionService, TranscriptionServiceException, GoogleProvider as VertexProvider, createSpeechHandler, extractJsonFromResponse, extractTextAndJson, handleApiError, sanitizeError };
720
+ export { AnthropicProvider, BaseConfigProvider$1 as BaseConfigProvider, ConfigManager, DefaultConfigProvider, FINISH_REASONS, GoogleProvider as GeminiProvider, GoogleProvider, LLMService, LLMServiceException, MODEL_CONFIGS, OpenAIProvider, TranscriptionService, TranscriptionServiceException, GoogleProvider as VertexProvider, createSpeechHandler, extractJsonFromResponse, extractTextAndJson, handleApiError, sanitizeError };
package/dist/index.js CHANGED
@@ -72,7 +72,8 @@ var DefaultConfigProvider = class extends BaseConfigProvider {
72
72
  return {
73
73
  provider: tenantConfig.provider,
74
74
  models: MODEL_CONFIGS[tenantConfig.provider],
75
- apiKey: tenantConfig.api_key,
75
+ // for backward compatibility, api_key is deprecated and shall never be used!!
76
+ apiKey: tenantConfig.apiKey || tenantConfig.api_key,
76
77
  project: tenantConfig.project,
77
78
  location: tenantConfig.location,
78
79
  temperature: parseFloat(env.DEFAULT_TEMPERATURE || "0.7"),
@@ -143,35 +144,36 @@ var DefaultConfigProvider = class extends BaseConfigProvider {
143
144
  // src/llm/config-manager.js
144
145
  var MODEL_CONFIGS = {
145
146
  openai: {
146
- default: "gpt-4o",
147
- edge: "gpt-4o",
148
- fast: "gpt-4o-mini",
149
- cost: "gpt-4o-mini",
150
- free: "gpt-4o-mini"
147
+ default: "gpt-5.5-instant",
148
+ edge: "gpt-5.5-thinking",
149
+ fast: "gpt-5.5-instant",
150
+ cost: "gpt-5.5-instant",
151
+ free: "gpt-5.5-instant"
151
152
  },
152
153
  gemini: {
153
- default: "gemini-3-flash-preview",
154
- // 'gemini-2.5-flash',
155
- edge: "gemini-3-pro-preview",
156
- // 'gemini-2.5-pro',
157
- fast: "gemini-3-flash-preview",
158
- // 'gemini-2.5-flash-lite',
159
- cost: "gemini-3-flash-preview",
160
- // 'gemini-2.5-flash-lite',
161
- free: "gemini-3-flash-preview",
162
- // 'gemini-2.0-flash-lite',
154
+ default: "gemini-3.5-flash",
155
+ edge: "gemini-3.5-pro",
156
+ fast: "gemini-3.5-flash",
157
+ cost: "gemini-3.5-flash",
158
+ free: "gemini-3.5-flash",
163
159
  video: "veo",
164
- image: "gemini-3-pro-image-preview"
165
- // Default image generation model
160
+ image: "gemini-3.5-pro-image-preview"
166
161
  },
167
162
  vertex: {
168
- default: "gemini-3-flash-preview",
169
- edge: "gemini-3-pro-preview",
170
- fast: "gemini-3-flash-preview",
171
- cost: "gemini-3-flash-preview",
172
- free: "gemini-3-flash-preview",
163
+ default: "gemini-3.5-flash",
164
+ edge: "gemini-3.5-pro",
165
+ fast: "gemini-3.5-flash",
166
+ cost: "gemini-3.5-flash",
167
+ free: "gemini-3.5-flash",
173
168
  video: "veo",
174
- image: "gemini-3-pro-image-preview"
169
+ image: "gemini-3.5-pro-image-preview"
170
+ },
171
+ anthropic: {
172
+ default: "claude-4.6-sonnet",
173
+ edge: "claude-4.8-opus",
174
+ fast: "claude-4.5-haiku",
175
+ cost: "claude-4.5-haiku",
176
+ free: "claude-4.5-haiku"
175
177
  }
176
178
  };
177
179
  var ConfigManager = class {
@@ -1131,6 +1133,170 @@ ${prompt}` : prompt;
1131
1133
  }
1132
1134
  };
1133
1135
 
1136
+ // src/llm/providers/anthropic-provider.js
1137
+ var AnthropicProvider = class extends BaseLLMProvider {
1138
+ constructor(config) {
1139
+ super(config);
1140
+ this.models = config.models || {};
1141
+ this.defaultModel = this.models.default || "claude-3-5-sonnet-20241022";
1142
+ }
1143
+ async chat(userMessage, systemPrompt = "", options = {}) {
1144
+ var _a;
1145
+ const messages = [{ role: "user", content: userMessage }];
1146
+ const tier = options.tier || "default";
1147
+ const effectiveModel = this._getModelForTier(tier);
1148
+ const effectiveMaxTokens = options.maxTokens || this.config.maxTokens || 4096;
1149
+ const effectiveTemperature = options.temperature !== void 0 ? options.temperature : (_a = this.config.temperature) != null ? _a : 0.7;
1150
+ const response = await this._chatCompletionWithModel(
1151
+ messages,
1152
+ systemPrompt,
1153
+ null,
1154
+ effectiveModel,
1155
+ effectiveMaxTokens,
1156
+ effectiveTemperature,
1157
+ options
1158
+ );
1159
+ return { text: response.content };
1160
+ }
1161
+ async chatCompletion(messages, systemPrompt, tools = null, options = {}) {
1162
+ var _a;
1163
+ const tier = options.tier || "default";
1164
+ const effectiveModel = this._getModelForTier(tier);
1165
+ const effectiveMaxTokens = options.maxTokens || this.config.maxTokens || 4096;
1166
+ const effectiveTemperature = options.temperature !== void 0 ? options.temperature : (_a = this.config.temperature) != null ? _a : 0.7;
1167
+ return this._chatCompletionWithModel(
1168
+ messages,
1169
+ systemPrompt,
1170
+ tools,
1171
+ effectiveModel,
1172
+ effectiveMaxTokens,
1173
+ effectiveTemperature,
1174
+ options
1175
+ );
1176
+ }
1177
+ async _chatCompletionWithModel(messages, systemPrompt, tools, modelName, maxTokens, temperature, options = {}) {
1178
+ const baseURL = this.config.baseURL || "https://api.anthropic.com";
1179
+ const url = `${baseURL.replace(/\/$/, "")}/v1/messages`;
1180
+ const formattedMessages = messages.map((m) => ({
1181
+ role: m.role === "assistant" ? "assistant" : "user",
1182
+ content: m.content
1183
+ }));
1184
+ const headers = {
1185
+ "Content-Type": "application/json",
1186
+ "x-api-key": this.config.apiKey || "",
1187
+ "anthropic-version": "2023-06-01"
1188
+ };
1189
+ const payload = {
1190
+ model: modelName,
1191
+ messages: formattedMessages,
1192
+ max_tokens: maxTokens,
1193
+ temperature
1194
+ };
1195
+ if (systemPrompt) {
1196
+ payload.system = systemPrompt;
1197
+ }
1198
+ if (options.responseFormat) {
1199
+ const formatType = typeof options.responseFormat === "string" ? options.responseFormat : options.responseFormat.type;
1200
+ if (formatType === "json" || formatType === "json_schema") {
1201
+ const schemaText = options.responseFormat.schema || options.responseSchema ? `
1202
+
1203
+ Your output must comply strictly with this JSON Schema: ${JSON.stringify(options.responseFormat.schema || options.responseSchema)}` : "";
1204
+ const jsonPrompt = `IMPORTANT: You must respond ONLY in raw JSON format. Do not write any conversational text, explanations, or markdown code blocks (e.g. do NOT wrap your answer in \`\`\`json ... \`\`\`). Your response must start with '{' and end with '}'.${schemaText}`;
1205
+ if (payload.system) {
1206
+ payload.system = `${payload.system}
1207
+
1208
+ ${jsonPrompt}`;
1209
+ } else {
1210
+ payload.system = jsonPrompt;
1211
+ }
1212
+ }
1213
+ }
1214
+ let responseText;
1215
+ let responseData;
1216
+ try {
1217
+ const res = await fetch(url, {
1218
+ method: "POST",
1219
+ headers,
1220
+ body: JSON.stringify(payload)
1221
+ });
1222
+ responseText = await res.text();
1223
+ if (!res.ok) {
1224
+ console.error(`[AnthropicProvider] API request failed with status ${res.status}:`, responseText);
1225
+ throw new LLMServiceException(`Anthropic API Error: ${responseText}`, res.status);
1226
+ }
1227
+ responseData = JSON.parse(responseText);
1228
+ } catch (error) {
1229
+ console.error(`[AnthropicProvider] request failed (API Key: ${this._getMaskedApiKey()}):`, error);
1230
+ throw error;
1231
+ }
1232
+ const contentBlock = responseData.content && responseData.content[0];
1233
+ const contentText = contentBlock ? contentBlock.text : "";
1234
+ if (!contentText) {
1235
+ console.error("[AnthropicProvider] Model returned empty response content");
1236
+ throw new LLMServiceException(
1237
+ "Model returned empty response. This usually means the prompt or schema is confusing the model.",
1238
+ 500
1239
+ );
1240
+ }
1241
+ const rawFinishReason = responseData.stop_reason;
1242
+ const normalizedFinishReason = this.normalizeFinishReason(rawFinishReason);
1243
+ const result = {
1244
+ content: contentText,
1245
+ tool_calls: null,
1246
+ // REST client tool calls mapping not required for playbook studio
1247
+ finishReason: normalizedFinishReason,
1248
+ _rawFinishReason: rawFinishReason,
1249
+ _responseFormat: options.responseFormat,
1250
+ usage: {
1251
+ prompt_tokens: responseData.usage ? responseData.usage.input_tokens : 0,
1252
+ completion_tokens: responseData.usage ? responseData.usage.output_tokens : 0,
1253
+ total_tokens: responseData.usage ? responseData.usage.input_tokens + responseData.usage.output_tokens : 0
1254
+ },
1255
+ model: modelName
1256
+ };
1257
+ if (options.responseFormat && this._shouldAutoParse(options)) {
1258
+ result.parsedContent = this._safeJsonParse(contentText);
1259
+ }
1260
+ return result;
1261
+ }
1262
+ _getModelForTier(tier) {
1263
+ if (this.models[tier]) {
1264
+ return this.models[tier];
1265
+ }
1266
+ return this.defaultModel;
1267
+ }
1268
+ _shouldAutoParse(options) {
1269
+ if (!options.responseFormat) return false;
1270
+ const formatType = typeof options.responseFormat === "string" ? options.responseFormat : options.responseFormat.type;
1271
+ return formatType === "json" || formatType === "json_schema";
1272
+ }
1273
+ _safeJsonParse(text) {
1274
+ try {
1275
+ return extractJsonFromResponse(text);
1276
+ } catch (error) {
1277
+ console.error("[AnthropicProvider] Failed to extract JSON from response:", text, error);
1278
+ try {
1279
+ return JSON.parse(text);
1280
+ } catch (_) {
1281
+ return null;
1282
+ }
1283
+ }
1284
+ }
1285
+ normalizeFinishReason(providerReason) {
1286
+ const lower = (providerReason || "").toLowerCase();
1287
+ if (lower === "end_turn") {
1288
+ return "completed";
1289
+ }
1290
+ if (lower === "max_tokens") {
1291
+ return "truncated";
1292
+ }
1293
+ if (lower === "stop_sequence") {
1294
+ return "completed";
1295
+ }
1296
+ return super.normalizeFinishReason(providerReason);
1297
+ }
1298
+ };
1299
+
1134
1300
  // src/llm-service.js
1135
1301
  var LLMService = class {
1136
1302
  constructor(env, toolImplementations = {}) {
@@ -1152,6 +1318,8 @@ var LLMService = class {
1152
1318
  provider = new OpenAIProvider(config);
1153
1319
  } else if (config.provider === "gemini" || config.provider === "vertex") {
1154
1320
  provider = new GoogleProvider(config);
1321
+ } else if (config.provider === "anthropic") {
1322
+ provider = new AnthropicProvider(config);
1155
1323
  } else {
1156
1324
  throw new LLMServiceException(`Unsupported LLM provider: ${config.provider}`, 500);
1157
1325
  }
@@ -1719,6 +1887,7 @@ function createSpeechHandler(app, getConfig) {
1719
1887
  return app;
1720
1888
  }
1721
1889
  export {
1890
+ AnthropicProvider,
1722
1891
  BaseConfigProvider,
1723
1892
  ConfigManager,
1724
1893
  DefaultConfigProvider,