@elizaos/plugin-openrouter 1.2.5 → 1.2.6

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.js CHANGED
@@ -28,8 +28,8 @@ function getLargeModel(runtime) {
28
28
  return getSetting(runtime, "OPENROUTER_LARGE_MODEL") ?? getSetting(
29
29
  runtime,
30
30
  "LARGE_MODEL",
31
- "google/gemini-2.5-flash-preview-05-20"
32
- ) ?? "google/gemini-2.5-flash-preview-05-20";
31
+ "openai/gpt-4.1-nano"
32
+ ) ?? "openai/gpt-4.1-nano";
33
33
  }
34
34
  function getImageModel(runtime) {
35
35
  return getSetting(runtime, "OPENROUTER_IMAGE_MODEL") ?? getSetting(runtime, "IMAGE_MODEL", "x-ai/grok-2-vision-1212") ?? "x-ai/grok-2-vision-1212";
@@ -78,10 +78,7 @@ function initializeOpenRouter(_config, runtime) {
78
78
  }
79
79
 
80
80
  // src/models/text.ts
81
- import {
82
- ModelType,
83
- logger as logger4
84
- } from "@elizaos/core";
81
+ import { logger as logger4, ModelType } from "@elizaos/core";
85
82
  import { generateText } from "ai";
86
83
 
87
84
  // src/providers/openrouter.ts
@@ -176,7 +173,8 @@ async function handleObjectGenerationError(error) {
176
173
  logger3.error(
177
174
  `[generateObject] Failed to parse repaired JSON: ${message}`
178
175
  );
179
- throw repairParseError instanceof Error ? repairParseError : new Error(message);
176
+ if (repairParseError instanceof Error) throw repairParseError;
177
+ throw Object.assign(new Error(message), { cause: repairParseError });
180
178
  }
181
179
  } else {
182
180
  logger3.error("[generateObject] JSON repair failed.");
@@ -185,7 +183,8 @@ async function handleObjectGenerationError(error) {
185
183
  } else {
186
184
  const message = error instanceof Error ? error.message : String(error);
187
185
  logger3.error(`[generateObject] Unknown error: ${message}`);
188
- throw error instanceof Error ? error : new Error(message);
186
+ if (error instanceof Error) throw error;
187
+ throw Object.assign(new Error(message), { cause: error });
189
188
  }
190
189
  }
191
190
 
@@ -224,6 +223,18 @@ async function generateTextWithModel(runtime, modelType, params) {
224
223
  if (toolChoice) {
225
224
  generateParams.toolChoice = toolChoice;
226
225
  }
226
+ let capturedToolResults = [];
227
+ let capturedToolCalls = [];
228
+ if (tools) {
229
+ generateParams.onStepFinish = async (stepResult) => {
230
+ if (stepResult.toolCalls && stepResult.toolCalls.length > 0) {
231
+ capturedToolCalls = [...capturedToolCalls, ...stepResult.toolCalls];
232
+ }
233
+ if (stepResult.toolResults && stepResult.toolResults.length > 0) {
234
+ capturedToolResults = [...capturedToolResults, ...stepResult.toolResults];
235
+ }
236
+ };
237
+ }
227
238
  const response = await generateText(generateParams);
228
239
  let responseText;
229
240
  if (tools && (!response.text || response.text.trim() === "" || response.text === "Tools executed successfully.")) {
@@ -234,6 +245,16 @@ async function generateTextWithModel(runtime, modelType, params) {
234
245
  if (response.usage) {
235
246
  emitModelUsageEvent(runtime, modelType, prompt, response.usage);
236
247
  }
248
+ if (tools && (capturedToolCalls.length > 0 || capturedToolResults.length > 0)) {
249
+ return {
250
+ text: responseText,
251
+ toolCalls: capturedToolCalls,
252
+ toolResults: capturedToolResults,
253
+ // Include other useful properties
254
+ usage: response.usage,
255
+ finishReason: response.finishReason
256
+ };
257
+ }
237
258
  return responseText;
238
259
  }
239
260
  async function handleTextSmall(runtime, params) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/init.ts","../src/utils/config.ts","../src/models/text.ts","../src/providers/openrouter.ts","../src/utils/events.ts","../src/utils/helpers.ts","../src/models/object.ts","../src/models/image.ts"],"sourcesContent":["import {\n ModelType,\n type Plugin,\n type IAgentRuntime,\n type GenerateTextParams,\n type ObjectGenerationParams,\n type ImageDescriptionParams,\n} from \"@elizaos/core\";\nimport type { Tool, ToolChoice } from \"ai\";\nimport { initializeOpenRouter } from \"./init\";\nimport { handleTextSmall, handleTextLarge } from \"./models/text\";\nimport { handleObjectSmall, handleObjectLarge } from \"./models/object\";\nimport { handleImageDescription } from \"./models/image\";\n\n/**\n * Defines the OpenRouter plugin with its name, description, and configuration options.\n * @type {Plugin}\n */\nexport const openrouterPlugin: Plugin = {\n name: \"openrouter\",\n description: \"OpenRouter plugin\",\n config: {\n OPENROUTER_API_KEY: process.env.OPENROUTER_API_KEY,\n OPENROUTER_BASE_URL: process.env.OPENROUTER_BASE_URL,\n OPENROUTER_SMALL_MODEL: process.env.OPENROUTER_SMALL_MODEL,\n OPENROUTER_LARGE_MODEL: process.env.OPENROUTER_LARGE_MODEL,\n OPENROUTER_IMAGE_MODEL: process.env.OPENROUTER_IMAGE_MODEL,\n SMALL_MODEL: process.env.SMALL_MODEL,\n LARGE_MODEL: process.env.LARGE_MODEL,\n IMAGE_MODEL: process.env.IMAGE_MODEL,\n },\n async init(config, runtime) {\n // Note: We intentionally don't await here because ElizaOS expects\n // the init method to return quickly. The initializeOpenRouter function\n // only performs synchronous validation and logging, so it's safe to\n // call without await. This prevents blocking the plugin initialization.\n initializeOpenRouter(config, runtime);\n },\n models: {\n [ModelType.TEXT_SMALL]: async (\n runtime: IAgentRuntime,\n params: GenerateTextParams & {\n tools?: Record<string, Tool>;\n toolChoice?: ToolChoice<Record<string, Tool>>;\n },\n ) => {\n return handleTextSmall(runtime, params);\n },\n [ModelType.TEXT_LARGE]: async (\n runtime: IAgentRuntime,\n params: GenerateTextParams & {\n tools?: Record<string, Tool>;\n toolChoice?: ToolChoice<Record<string, Tool>>;\n },\n ) => {\n return handleTextLarge(runtime, params);\n },\n [ModelType.OBJECT_SMALL]: async (\n runtime: IAgentRuntime,\n params: ObjectGenerationParams,\n ) => {\n return handleObjectSmall(runtime, params);\n },\n [ModelType.OBJECT_LARGE]: async (\n runtime: IAgentRuntime,\n params: ObjectGenerationParams,\n ) => {\n return handleObjectLarge(runtime, params);\n },\n [ModelType.IMAGE_DESCRIPTION]: async (\n runtime: IAgentRuntime,\n params: ImageDescriptionParams | string,\n ) => {\n return handleImageDescription(runtime, params);\n },\n },\n};\n\nexport default openrouterPlugin;\n","import { logger, type IAgentRuntime } from \"@elizaos/core\";\nimport { fetch } from \"undici\";\nimport { getApiKey, getBaseURL } from \"./utils/config\";\n\n/**\n * Initialize and validate OpenRouter configuration\n * Returns the exact same function that works inline\n */\nexport function initializeOpenRouter(_config: any, runtime: IAgentRuntime) {\n // do check in the background\n (async () => {\n try {\n if (!getApiKey(runtime)) {\n logger.warn(\n \"OPENROUTER_API_KEY is not set in environment - OpenRouter functionality will be limited\",\n );\n return;\n }\n try {\n const baseURL = getBaseURL(runtime);\n const response = await fetch(`${baseURL}/models`, {\n headers: { Authorization: `Bearer ${getApiKey(runtime)}` },\n });\n if (!response.ok) {\n logger.warn(\n `OpenRouter API key validation failed: ${response.statusText}`,\n );\n logger.warn(\n \"OpenRouter functionality will be limited until a valid API key is provided\",\n );\n } else {\n logger.log(\"OpenRouter API key validated successfully\");\n }\n } catch (fetchError: unknown) {\n const message =\n fetchError instanceof Error ? fetchError.message : String(fetchError);\n logger.warn(`Error validating OpenRouter API key: ${message}`);\n logger.warn(\n \"OpenRouter functionality will be limited until a valid API key is provided\",\n );\n }\n } catch (error: unknown) {\n const message =\n (error as { errors?: Array<{ message: string }> })?.errors\n ?.map((e) => e.message)\n .join(\", \") ||\n (error instanceof Error ? error.message : String(error));\n logger.warn(\n `OpenRouter plugin configuration issue: ${message} - You need to configure the OPENROUTER_API_KEY in your environment variables`,\n );\n }\n })();\n return;\n}\n","import type { IAgentRuntime } from \"@elizaos/core\";\n\n/**\n * Retrieves a configuration setting from the runtime, falling back to environment variables or a default value if not found.\n *\n * @param key - The name of the setting to retrieve.\n * @param defaultValue - The value to return if the setting is not found in the runtime or environment.\n * @returns The resolved setting value, or {@link defaultValue} if not found.\n */\nexport function getSetting(\n runtime: IAgentRuntime,\n key: string,\n defaultValue?: string,\n): string | undefined {\n return runtime.getSetting(key) ?? process.env[key] ?? defaultValue;\n}\n\n/**\n * Retrieves the OpenRouter API base URL from runtime settings, environment variables, or defaults.\n *\n * @returns The resolved base URL for OpenRouter API requests.\n */\nexport function getBaseURL(runtime: IAgentRuntime): string {\n return (\n getSetting(\n runtime,\n \"OPENROUTER_BASE_URL\",\n \"https://openrouter.ai/api/v1\",\n ) || \"https://openrouter.ai/api/v1\"\n );\n}\n\n/**\n * Helper function to get the API key for OpenRouter\n *\n * @param runtime The runtime context\n * @returns The configured API key\n */\nexport function getApiKey(runtime: IAgentRuntime): string | undefined {\n return getSetting(runtime, \"OPENROUTER_API_KEY\");\n}\n\n/**\n * Helper function to get the small model name with fallbacks\n *\n * @param runtime The runtime context\n * @returns The configured small model name\n */\nexport function getSmallModel(runtime: IAgentRuntime): string {\n return (\n getSetting(runtime, \"OPENROUTER_SMALL_MODEL\") ??\n getSetting(runtime, \"SMALL_MODEL\", \"google/gemini-2.0-flash-001\") ??\n \"google/gemini-2.0-flash-001\"\n );\n}\n\n/**\n * Helper function to get the large model name with fallbacks\n *\n * @param runtime The runtime context\n * @returns The configured large model name\n */\nexport function getLargeModel(runtime: IAgentRuntime): string {\n return (\n getSetting(runtime, \"OPENROUTER_LARGE_MODEL\") ??\n getSetting(\n runtime,\n \"LARGE_MODEL\",\n \"google/gemini-2.5-flash-preview-05-20\",\n ) ??\n \"google/gemini-2.5-flash-preview-05-20\"\n );\n}\n\n/**\n * Helper function to get the image model name with fallbacks\n *\n * @param runtime The runtime context\n * @returns The configured image model name\n */\nexport function getImageModel(runtime: IAgentRuntime): string {\n return (\n getSetting(runtime, \"OPENROUTER_IMAGE_MODEL\") ??\n getSetting(runtime, \"IMAGE_MODEL\", \"x-ai/grok-2-vision-1212\") ??\n \"x-ai/grok-2-vision-1212\"\n );\n}\n","import {\n ModelType,\n logger,\n type IAgentRuntime,\n type GenerateTextParams,\n} from \"@elizaos/core\";\nimport type { Tool, ToolChoice } from \"ai\";\nimport { generateText } from \"ai\";\nimport { createOpenRouterProvider } from \"../providers\";\nimport { getSmallModel, getLargeModel } from \"../utils/config\";\nimport { emitModelUsageEvent } from \"../utils/events\";\nimport { handleEmptyToolResponse } from \"../utils/helpers\";\n\n/**\n * Common text generation logic for both small and large models\n */\nasync function generateTextWithModel(\n runtime: IAgentRuntime,\n modelType: typeof ModelType.TEXT_SMALL | typeof ModelType.TEXT_LARGE,\n params: GenerateTextParams & {\n tools?: Record<string, Tool>;\n toolChoice?: ToolChoice<Record<string, Tool>>;\n },\n): Promise<string> {\n const { prompt, stopSequences = [], tools, toolChoice } = params;\n const temperature = params.temperature ?? 0.7;\n const frequencyPenalty = params.frequencyPenalty ?? 0.7;\n const presencePenalty = params.presencePenalty ?? 0.7;\n const maxResponseLength = params.maxTokens ?? 8192;\n\n const openrouter = createOpenRouterProvider(runtime);\n const modelName =\n modelType === ModelType.TEXT_SMALL\n ? getSmallModel(runtime)\n : getLargeModel(runtime);\n const modelLabel =\n modelType === ModelType.TEXT_SMALL ? \"TEXT_SMALL\" : \"TEXT_LARGE\";\n\n logger.log(\n `[OpenRouter] Generating text with ${modelLabel} model: ${modelName}`,\n );\n\n const generateParams: Parameters<typeof generateText>[0] & {\n extra_body?: { provider?: { require_parameters?: boolean } };\n } = {\n model: openrouter.chat(modelName),\n prompt: prompt,\n system: runtime.character.system ?? undefined,\n temperature: temperature,\n maxTokens: maxResponseLength,\n frequencyPenalty: frequencyPenalty,\n presencePenalty: presencePenalty,\n stopSequences: stopSequences,\n };\n\n // Add tools if provided\n if (tools) {\n generateParams.tools = tools;\n generateParams.maxSteps = 10; // Allow tool call + response generation\n // For OpenRouter: ensure request is only routed to providers that support function calling\n generateParams.extra_body = {\n provider: {\n require_parameters: true,\n },\n };\n }\n\n // Add toolChoice if provided\n if (toolChoice) {\n generateParams.toolChoice = toolChoice;\n }\n\n const response = await generateText(generateParams);\n\n // Handle cases where tool execution doesn't generate text\n let responseText: string;\n if (\n tools &&\n (!response.text ||\n response.text.trim() === \"\" ||\n response.text === \"Tools executed successfully.\")\n ) {\n responseText = handleEmptyToolResponse(modelLabel);\n } else {\n responseText = response.text;\n }\n\n if (response.usage) {\n emitModelUsageEvent(runtime, modelType, prompt, response.usage);\n }\n\n return responseText;\n}\n\n/**\n * TEXT_SMALL model handler\n */\nexport async function handleTextSmall(\n runtime: IAgentRuntime,\n params: GenerateTextParams & {\n tools?: Record<string, Tool>;\n toolChoice?: ToolChoice<Record<string, Tool>>;\n },\n): Promise<string> {\n return generateTextWithModel(runtime, ModelType.TEXT_SMALL, params);\n}\n\n/**\n * TEXT_LARGE model handler\n */\nexport async function handleTextLarge(\n runtime: IAgentRuntime,\n params: GenerateTextParams & {\n tools?: Record<string, Tool>;\n toolChoice?: ToolChoice<Record<string, Tool>>;\n },\n): Promise<string> {\n return generateTextWithModel(runtime, ModelType.TEXT_LARGE, params);\n}\n","import { createOpenRouter } from \"@openrouter/ai-sdk-provider\";\nimport { logger, type IAgentRuntime } from \"@elizaos/core\";\nimport { getApiKey } from \"../utils/config\";\n\n/**\n * Create an OpenRouter provider instance with proper configuration\n *\n * @param runtime The runtime context\n * @returns Configured OpenRouter provider instance\n */\nexport function createOpenRouterProvider(runtime: IAgentRuntime) {\n const apiKey = getApiKey(runtime);\n if (!apiKey) {\n // This case should ideally be caught in init, but good practice to check\n logger.error(\n \"OpenRouter API Key is missing when trying to create provider\",\n );\n throw new Error(\"OpenRouter API Key is missing.\");\n }\n\n // Note: createOpenRouter doesn't seem to take baseURL directly in the documentation.\n // It might pick it up from OPENROUTER_BASE_URL env var automatically,\n // or it might not be needed/configurable in the same way as createOpenRouter.\n // We'll rely on the apiKey for now.\n return createOpenRouter({\n apiKey: apiKey,\n // We might need to handle baseURL differently if required.\n // The @ai-sdk/provider utils might handle OPENROUTER_BASE_URL env var.\n });\n}\n","import {\n EventType,\n type IAgentRuntime,\n type ModelTypeName,\n} from \"@elizaos/core\";\nimport type { LanguageModelUsage } from \"ai\";\n\n/**\n * Emits a model usage event\n */\nexport function emitModelUsageEvent(\n runtime: IAgentRuntime,\n type: ModelTypeName,\n prompt: string,\n usage: LanguageModelUsage,\n) {\n runtime.emitEvent(EventType.MODEL_USED, {\n provider: \"openrouter\",\n type,\n prompt,\n tokens: {\n prompt: usage.promptTokens,\n completion: usage.completionTokens,\n total: usage.totalTokens,\n },\n });\n}\n","import { logger } from \"@elizaos/core\";\nimport { JSONParseError } from \"ai\";\nimport type { GenerateTextResponse, ImageDescriptionResult } from \"../types\";\nimport { emitModelUsageEvent } from \"./events\";\n\n/**\n * Returns a function to repair JSON text\n */\nexport function getJsonRepairFunction(): (params: {\n text: string;\n error: unknown;\n}) => Promise<string | null> {\n return async ({ text, error }: { text: string; error: unknown }) => {\n try {\n if (error instanceof JSONParseError) {\n const cleanedText = text.replace(/```json\\n|\\n```|```/g, \"\");\n JSON.parse(cleanedText);\n return cleanedText;\n }\n return null;\n } catch (jsonError: unknown) {\n const message =\n jsonError instanceof Error ? jsonError.message : String(jsonError);\n logger.warn(`Failed to repair JSON text: ${message}`);\n return null;\n }\n };\n}\n\n// Re-export for backward compatibility\nexport { emitModelUsageEvent } from \"./events\";\n\n/**\n * Logs response structure for debugging (debug level only)\n */\nexport function logResponseStructure(\n modelType: string,\n response: GenerateTextResponse,\n) {\n logger.debug(`[${modelType}] Response structure:`, {\n hasText: !!response.text,\n textLength: response.text?.length || 0,\n hasSteps: !!response.steps,\n stepsCount: response.steps?.length || 0,\n finishReason: response.finishReason,\n usage: response.usage,\n });\n}\n\n/**\n * Handles cases where tool execution doesn't generate text\n */\nexport function handleEmptyToolResponse(modelType: string): string {\n logger.warn(`[${modelType}] No text generated after tool execution`);\n\n const fallbackText =\n \"I executed the requested action. The tool completed successfully.\";\n logger.warn(`[${modelType}] Using fallback response text`);\n return fallbackText;\n}\n\n/**\n * Parses image description response from text or JSON format\n */\nexport function parseImageDescriptionResponse(\n responseText: string,\n): ImageDescriptionResult {\n // Try to parse as JSON first\n try {\n const jsonResponse = JSON.parse(responseText);\n if (jsonResponse.title && jsonResponse.description) {\n return jsonResponse;\n }\n } catch (e) {\n // If not valid JSON, process as text\n logger.debug(`Parsing as JSON failed, processing as text: ${e}`);\n }\n\n // Extract title and description from text format\n const titleMatch = responseText.match(/title[:\\s]+(.+?)(?:\\n|$)/i);\n const title = titleMatch?.[1]?.trim() || \"Image Analysis\";\n const description = responseText\n .replace(/title[:\\s]+(.+?)(?:\\n|$)/i, \"\")\n .trim();\n\n return { title, description };\n}\n\n/**\n * Handles errors during object generation, including JSON repair attempts\n */\nexport async function handleObjectGenerationError(\n error: unknown,\n): Promise<unknown> {\n if (error instanceof JSONParseError) {\n logger.error(`[generateObject] Failed to parse JSON: ${error.message}`);\n const repairFunction = getJsonRepairFunction();\n const repairedJsonString = await repairFunction({\n text: error.text,\n error,\n });\n\n if (repairedJsonString) {\n try {\n const repairedObject = JSON.parse(repairedJsonString);\n logger.log(\"[generateObject] Successfully repaired JSON.\");\n return repairedObject;\n } catch (repairParseError: unknown) {\n const message =\n repairParseError instanceof Error\n ? repairParseError.message\n : String(repairParseError);\n logger.error(\n `[generateObject] Failed to parse repaired JSON: ${message}`,\n );\n throw repairParseError instanceof Error\n ? repairParseError\n : new Error(message);\n }\n } else {\n logger.error(\"[generateObject] JSON repair failed.\");\n throw error;\n }\n } else {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`[generateObject] Unknown error: ${message}`);\n throw error instanceof Error ? error : new Error(message);\n }\n}\n","import {\n ModelType,\n logger,\n type IAgentRuntime,\n type ObjectGenerationParams,\n} from \"@elizaos/core\";\nimport { generateObject } from \"ai\";\nimport { createOpenRouterProvider } from \"../providers\";\nimport { getSmallModel, getLargeModel } from \"../utils/config\";\nimport { emitModelUsageEvent } from \"../utils/events\";\nimport {\n getJsonRepairFunction,\n handleObjectGenerationError,\n} from \"../utils/helpers\";\n\n/**\n * Common object generation logic for both small and large models\n */\nasync function generateObjectWithModel(\n runtime: IAgentRuntime,\n modelType: typeof ModelType.OBJECT_SMALL | typeof ModelType.OBJECT_LARGE,\n params: ObjectGenerationParams,\n): Promise<unknown> {\n const openrouter = createOpenRouterProvider(runtime);\n const modelName =\n modelType === ModelType.OBJECT_SMALL\n ? getSmallModel(runtime)\n : getLargeModel(runtime);\n const modelLabel =\n modelType === ModelType.OBJECT_SMALL ? \"OBJECT_SMALL\" : \"OBJECT_LARGE\";\n\n logger.log(`[OpenRouter] Using ${modelLabel} model: ${modelName}`);\n const temperature = params.temperature ?? 0.7;\n\n try {\n const { object, usage } = await generateObject({\n model: openrouter.chat(modelName),\n output: \"no-schema\",\n prompt: params.prompt,\n temperature: temperature,\n experimental_repairText: getJsonRepairFunction(),\n });\n\n if (usage) {\n emitModelUsageEvent(runtime, modelType, params.prompt, usage);\n }\n return object;\n } catch (error: unknown) {\n return handleObjectGenerationError(error);\n }\n}\n\n/**\n * OBJECT_SMALL model handler\n */\nexport async function handleObjectSmall(\n runtime: IAgentRuntime,\n params: ObjectGenerationParams,\n): Promise<unknown> {\n return generateObjectWithModel(runtime, ModelType.OBJECT_SMALL, params);\n}\n\n/**\n * OBJECT_LARGE model handler\n */\nexport async function handleObjectLarge(\n runtime: IAgentRuntime,\n params: ObjectGenerationParams,\n): Promise<unknown> {\n return generateObjectWithModel(runtime, ModelType.OBJECT_LARGE, params);\n}\n","import {\n logger,\n type IAgentRuntime,\n type ImageDescriptionParams,\n} from \"@elizaos/core\";\nimport { generateText } from \"ai\";\nimport { createOpenRouterProvider } from \"../providers\";\nimport { getImageModel } from \"../utils/config\";\nimport { parseImageDescriptionResponse } from \"../utils/helpers\";\n\n/**\n * IMAGE_DESCRIPTION model handler\n */\nexport async function handleImageDescription(\n runtime: IAgentRuntime,\n params: ImageDescriptionParams | string,\n): Promise<{ title: string; description: string }> {\n let imageUrl: string;\n let promptText: string | undefined;\n const modelName = getImageModel(runtime);\n logger.log(`[OpenRouter] Using IMAGE_DESCRIPTION model: ${modelName}`);\n const maxTokens = 300;\n\n if (typeof params === \"string\") {\n imageUrl = params;\n promptText =\n \"Please analyze this image and provide a title and detailed description.\";\n } else {\n imageUrl = params.imageUrl;\n promptText =\n params.prompt ||\n \"Please analyze this image and provide a title and detailed description.\";\n }\n\n const openrouter = createOpenRouterProvider(runtime);\n\n const messages = [\n {\n role: \"user\" as const,\n content: [\n { type: \"text\" as const, text: promptText },\n { type: \"image\" as const, image: imageUrl },\n ],\n },\n ];\n\n try {\n const model = openrouter.chat(modelName);\n\n const { text: responseText } = await generateText({\n model: model,\n messages: messages,\n maxTokens: maxTokens,\n });\n\n return parseImageDescriptionResponse(responseText);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error analyzing image: ${message}`);\n return {\n title: \"Failed to analyze image\",\n description: `Error: ${message}`,\n };\n }\n}\n"],"mappings":";AAAA;AAAA,EACE,aAAAA;AAAA,OAMK;;;ACPP,SAAS,cAAkC;AAC3C,SAAS,aAAa;;;ACQf,SAAS,WACd,SACA,KACA,cACoB;AACpB,SAAO,QAAQ,WAAW,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK;AACxD;AAOO,SAAS,WAAW,SAAgC;AACzD,SACE;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EACF,KAAK;AAET;AAQO,SAAS,UAAU,SAA4C;AACpE,SAAO,WAAW,SAAS,oBAAoB;AACjD;AAQO,SAAS,cAAc,SAAgC;AAC5D,SACE,WAAW,SAAS,wBAAwB,KAC5C,WAAW,SAAS,eAAe,6BAA6B,KAChE;AAEJ;AAQO,SAAS,cAAc,SAAgC;AAC5D,SACE,WAAW,SAAS,wBAAwB,KAC5C;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,EACF,KACA;AAEJ;AAQO,SAAS,cAAc,SAAgC;AAC5D,SACE,WAAW,SAAS,wBAAwB,KAC5C,WAAW,SAAS,eAAe,yBAAyB,KAC5D;AAEJ;;;AD9EO,SAAS,qBAAqB,SAAc,SAAwB;AAEzE,GAAC,YAAY;AACX,QAAI;AACF,UAAI,CAAC,UAAU,OAAO,GAAG;AACvB,eAAO;AAAA,UACL;AAAA,QACF;AACA;AAAA,MACF;AACA,UAAI;AACF,cAAM,UAAU,WAAW,OAAO;AAClC,cAAM,WA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UAAU,OAAO;AAAA,IAChC;AAAA,EACF;AACF;;;AR9CO,IAAM,mBAA2B;AAAA,EACtC,MAAM;AAAA,EACN,aAAa;AAAA,EACb,QAAQ;AAAA,IACN,oBAAoB,QAAQ,IAAI;AAAA,IAChC,qBAAqB,QAAQ,IAAI;AAAA,IACjC,wBAAwB,QAAQ,IAAI;AAAA,IACpC,wBAAwB,QAAQ,IAAI;AAAA,IACpC,wBAAwB,QAAQ,IAAI;AAAA,IACpC,aAAa,QAAQ,IAAI;AAAA,IACzB,aAAa,QAAQ,IAAI;AAAA,IACzB,aAAa,QAAQ,IAAI;AAAA,EAC3B;AAAA,EACA,MAAM,KAAK,QAAQ,SAAS;AAK1B,yBAAqB,QAAQ,OAAO;AAAA,EACtC;AAAA,EACA,QAAQ;AAAA,IACN,CAACE,WAAU,UAAU,GAAG,OACtB,SACA,WAIG;AACH,aAAO,gBAAgB,SAAS,MAAM;AAAA,IACxC;AAAA,IACA,CAACA,WAAU,UAAU,GAAG,OACtB,SACA,WAIG;AACH,aAAO,gBAAgB,SAAS,MAAM;AAAA,IACxC;AAAA,IACA,CAACA,WAAU,YAAY,GAAG,OACxB,SACA,WACG;AACH,aAAO,kBAAkB,SAAS,MAAM;AAAA,IAC1C;AAAA,IACA,CAACA,WAAU,YAAY,GAAG,OACxB,SACA,WACG;AACH,aAAO,kBAAkB,SAAS,MAAM;AAAA,IAC1C;AAAA,IACA,CAACA,WAAU,iBAAiB,GAAG,OAC7B,SACA,WACG;AACH,aAAO,uBAAuB,SAAS,MAAM;AAAA,IAC/C;AAAA,EACF;AACF;AAEA,IAAO,gBAAQ;","names":["ModelType","logger","logger","logger","logger","logger","logger","ModelType","logger","ModelType","logger","logger","generateText","logger","generateText","ModelType"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/init.ts","../src/utils/config.ts","../src/models/text.ts","../src/providers/openrouter.ts","../src/utils/events.ts","../src/utils/helpers.ts","../src/models/object.ts","../src/models/image.ts"],"sourcesContent":["import {\n\tModelType,\n\ttype Plugin,\n\ttype IAgentRuntime,\n\ttype GenerateTextParams,\n\ttype ObjectGenerationParams,\n\ttype ImageDescriptionParams,\n} from \"@elizaos/core\";\nimport type { Tool, ToolChoice } from \"ai\";\nimport { initializeOpenRouter } from \"./init\";\nimport { handleTextSmall, handleTextLarge } from \"./models/text\";\nimport { handleObjectSmall, handleObjectLarge } from \"./models/object\";\nimport { handleImageDescription } from \"./models/image\";\n\n/**\n * Defines the OpenRouter plugin with its name, description, and configuration options.\n * @type {Plugin}\n */\nexport const openrouterPlugin: Plugin = {\n\tname: \"openrouter\",\n\tdescription: \"OpenRouter plugin\",\n\tconfig: {\n\t\tOPENROUTER_API_KEY: process.env.OPENROUTER_API_KEY,\n\t\tOPENROUTER_BASE_URL: process.env.OPENROUTER_BASE_URL,\n\t\tOPENROUTER_SMALL_MODEL: process.env.OPENROUTER_SMALL_MODEL,\n\t\tOPENROUTER_LARGE_MODEL: process.env.OPENROUTER_LARGE_MODEL,\n\t\tOPENROUTER_IMAGE_MODEL: process.env.OPENROUTER_IMAGE_MODEL,\n\t\tSMALL_MODEL: process.env.SMALL_MODEL,\n\t\tLARGE_MODEL: process.env.LARGE_MODEL,\n\t\tIMAGE_MODEL: process.env.IMAGE_MODEL,\n\t},\n\tasync init(config, runtime) {\n\t\t// Note: We intentionally don't await here because ElizaOS expects\n\t\t// the init method to return quickly. The initializeOpenRouter function\n\t\t// only performs synchronous validation and logging, so it's safe to\n\t\t// call without await. This prevents blocking the plugin initialization.\n\t\tinitializeOpenRouter(config, runtime);\n\t},\n\tmodels: {\n\t\t[ModelType.TEXT_SMALL]: async (\n\t\t\truntime: IAgentRuntime,\n\t\t\tparams: GenerateTextParams & {\n\t\t\t\ttools?: Record<string, Tool>;\n\t\t\t\ttoolChoice?: ToolChoice<Record<string, Tool>>;\n\t\t\t},\n\t\t) => {\n\t\t\treturn handleTextSmall(runtime, params);\n\t\t},\n\t\t[ModelType.TEXT_LARGE]: async (\n\t\t\truntime: IAgentRuntime,\n\t\t\tparams: GenerateTextParams & {\n\t\t\t\ttools?: Record<string, Tool>;\n\t\t\t\ttoolChoice?: ToolChoice<Record<string, Tool>>;\n\t\t\t},\n\t\t) => {\n\t\t\treturn handleTextLarge(runtime, params);\n\t\t},\n\t\t[ModelType.OBJECT_SMALL]: async (\n\t\t\truntime: IAgentRuntime,\n\t\t\tparams: ObjectGenerationParams,\n\t\t) => {\n\t\t\treturn handleObjectSmall(runtime, params);\n\t\t},\n\t\t[ModelType.OBJECT_LARGE]: async (\n\t\t\truntime: IAgentRuntime,\n\t\t\tparams: ObjectGenerationParams,\n\t\t) => {\n\t\t\treturn handleObjectLarge(runtime, params);\n\t\t},\n\t\t[ModelType.IMAGE_DESCRIPTION]: async (\n\t\t\truntime: IAgentRuntime,\n\t\t\tparams: ImageDescriptionParams | string,\n\t\t) => {\n\t\t\treturn handleImageDescription(runtime, params);\n\t\t},\n\t},\n};\n\nexport default openrouterPlugin;\n","import { logger, type IAgentRuntime } from \"@elizaos/core\";\nimport { fetch } from \"undici\";\nimport { getApiKey, getBaseURL } from \"./utils/config\";\n\n/**\n * Initialize and validate OpenRouter configuration\n * Returns the exact same function that works inline\n */\nexport function initializeOpenRouter(_config: any, runtime: IAgentRuntime) {\n\t// do check in the background\n\t(async () => {\n\t\ttry {\n\t\t\tif (!getApiKey(runtime)) {\n\t\t\t\tlogger.warn(\n\t\t\t\t\t\"OPENROUTER_API_KEY is not set in environment - OpenRouter functionality will be limited\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst baseURL = getBaseURL(runtime);\n\t\t\t\tconst response = await fetch(`${baseURL}/models`, {\n\t\t\t\t\theaders: { Authorization: `Bearer ${getApiKey(runtime)}` },\n\t\t\t\t});\n\t\t\t\tif (!response.ok) {\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t`OpenRouter API key validation failed: ${response.statusText}`,\n\t\t\t\t\t);\n\t\t\t\t\tlogger.warn(\n\t\t\t\t\t\t\"OpenRouter functionality will be limited until a valid API key is provided\",\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tlogger.log(\"OpenRouter API key validated successfully\");\n\t\t\t\t}\n\t\t\t} catch (fetchError: unknown) {\n\t\t\t\tconst message =\n\t\t\t\t\tfetchError instanceof Error ? fetchError.message : String(fetchError);\n\t\t\t\tlogger.warn(`Error validating OpenRouter API key: ${message}`);\n\t\t\t\tlogger.warn(\n\t\t\t\t\t\"OpenRouter functionality will be limited until a valid API key is provided\",\n\t\t\t\t);\n\t\t\t}\n\t\t} catch (error: unknown) {\n\t\t\tconst message =\n\t\t\t\t(error as { errors?: Array<{ message: string }> })?.errors\n\t\t\t\t\t?.map((e) => e.message)\n\t\t\t\t\t.join(\", \") ||\n\t\t\t\t(error instanceof Error ? error.message : String(error));\n\t\t\tlogger.warn(\n\t\t\t\t`OpenRouter plugin configuration issue: ${message} - You need to configure the OPENROUTER_API_KEY in your environment variables`,\n\t\t\t);\n\t\t}\n\t})();\n\treturn;\n}\n","import type { IAgentRuntime } from \"@elizaos/core\";\n\n/**\n * Retrieves a configuration setting from the runtime, falling back to environment variables or a default value if not found.\n *\n * @param key - The name of the setting to retrieve.\n * @param defaultValue - The value to return if the setting is not found in the runtime or environment.\n * @returns The resolved setting value, or {@link defaultValue} if not found.\n */\nexport function getSetting(\n\truntime: IAgentRuntime,\n\tkey: string,\n\tdefaultValue?: string,\n): string | undefined {\n\treturn runtime.getSetting(key) ?? process.env[key] ?? defaultValue;\n}\n\n/**\n * Retrieves the OpenRouter API base URL from runtime settings, environment variables, or defaults.\n *\n * @returns The resolved base URL for OpenRouter API requests.\n */\nexport function getBaseURL(runtime: IAgentRuntime): string {\n\treturn (\n\t\tgetSetting(\n\t\t\truntime,\n\t\t\t\"OPENROUTER_BASE_URL\",\n\t\t\t\"https://openrouter.ai/api/v1\",\n\t\t) || \"https://openrouter.ai/api/v1\"\n\t);\n}\n\n/**\n * Helper function to get the API key for OpenRouter\n *\n * @param runtime The runtime context\n * @returns The configured API key\n */\nexport function getApiKey(runtime: IAgentRuntime): string | undefined {\n\treturn getSetting(runtime, \"OPENROUTER_API_KEY\");\n}\n\n/**\n * Helper function to get the small model name with fallbacks\n *\n * @param runtime The runtime context\n * @returns The configured small model name\n */\nexport function getSmallModel(runtime: IAgentRuntime): string {\n\treturn (\n\t\tgetSetting(runtime, \"OPENROUTER_SMALL_MODEL\") ??\n\t\tgetSetting(runtime, \"SMALL_MODEL\", \"google/gemini-2.0-flash-001\") ??\n\t\t\"google/gemini-2.0-flash-001\"\n\t);\n}\n\n/**\n * Helper function to get the large model name with fallbacks\n *\n * @param runtime The runtime context\n * @returns The configured large model name\n */\nexport function getLargeModel(runtime: IAgentRuntime): string {\n\treturn (\n\t\tgetSetting(runtime, \"OPENROUTER_LARGE_MODEL\") ??\n\t\tgetSetting(\n\t\t\truntime,\n\t\t\t\"LARGE_MODEL\",\n\t\t\t\"openai/gpt-4.1-nano\",\n\t\t) ??\n\t\t\"openai/gpt-4.1-nano\"\n\t);\n}\n\n/**\n * Helper function to get the image model name with fallbacks\n *\n * @param runtime The runtime context\n * @returns The configured image model name\n */\nexport function getImageModel(runtime: IAgentRuntime): string {\n\treturn (\n\t\tgetSetting(runtime, \"OPENROUTER_IMAGE_MODEL\") ??\n\t\tgetSetting(runtime, \"IMAGE_MODEL\", \"x-ai/grok-2-vision-1212\") ??\n\t\t\"x-ai/grok-2-vision-1212\"\n\t);\n}\n","import type { GenerateTextParams, IAgentRuntime } from \"@elizaos/core\";\nimport { logger, ModelType } from \"@elizaos/core\";\nimport { generateText } from \"ai\";\nimport type { Tool, ToolChoice } from \"ai\";\n\nimport { createOpenRouterProvider } from \"../providers\";\nimport type { ToolCall, ToolResponse, ToolResult } from \"../types\";\nimport { getSmallModel, getLargeModel } from \"../utils/config\";\nimport { emitModelUsageEvent } from \"../utils/events\";\nimport { handleEmptyToolResponse } from \"../utils/helpers\";\n\n/**\n * Common text generation logic for both small and large models\n */\nasync function generateTextWithModel(\n\truntime: IAgentRuntime,\n\tmodelType: typeof ModelType.TEXT_SMALL | typeof ModelType.TEXT_LARGE,\n\tparams: GenerateTextParams & {\n\t\ttools?: Record<string, Tool>;\n\t\ttoolChoice?: ToolChoice<Record<string, Tool>>;\n\t},\n): Promise<string | ToolResponse> {\n\tconst { prompt, stopSequences = [], tools, toolChoice } = params;\n\tconst temperature = params.temperature ?? 0.7;\n\tconst frequencyPenalty = params.frequencyPenalty ?? 0.7;\n\tconst presencePenalty = params.presencePenalty ?? 0.7;\n\tconst maxResponseLength = params.maxTokens ?? 8192;\n\n\tconst openrouter = createOpenRouterProvider(runtime);\n\tconst modelName =\n\t\tmodelType === ModelType.TEXT_SMALL\n\t\t\t? getSmallModel(runtime)\n\t\t\t: getLargeModel(runtime);\n\tconst modelLabel =\n\t\tmodelType === ModelType.TEXT_SMALL ? \"TEXT_SMALL\" : \"TEXT_LARGE\";\n\n\tlogger.log(\n\t\t`[OpenRouter] Generating text with ${modelLabel} model: ${modelName}`,\n\t);\n\n\tconst generateParams: Parameters<typeof generateText>[0] & {\n\t\textra_body?: { provider?: { require_parameters?: boolean } };\n\t} = {\n\t\tmodel: openrouter.chat(modelName),\n\t\tprompt: prompt,\n\t\tsystem: runtime.character.system ?? undefined,\n\t\ttemperature: temperature,\n\t\tmaxTokens: maxResponseLength,\n\t\tfrequencyPenalty: frequencyPenalty,\n\t\tpresencePenalty: presencePenalty,\n\t\tstopSequences: stopSequences,\n\t};\n\n\t// Add tools if provided\n\tif (tools) {\n\t\tgenerateParams.tools = tools;\n\t\tgenerateParams.maxSteps = 10; // Allow tool call + response generation\n\t\t// For OpenRouter: ensure request is only routed to providers that support function calling\n\t\tgenerateParams.extra_body = {\n\t\t\tprovider: {\n\t\t\t\trequire_parameters: true,\n\t\t\t},\n\t\t};\n\t}\n\n\t// Add toolChoice if provided\n\tif (toolChoice) {\n\t\tgenerateParams.toolChoice = toolChoice;\n\t}\n\n\t// Capture tool results if tools are used\n\tlet capturedToolResults: ToolResult[] = [];\n\tlet capturedToolCalls: ToolCall[] = [];\n\n\tif (tools) {\n\t\tgenerateParams.onStepFinish = async (stepResult) => {\n\t\t\tif (stepResult.toolCalls && stepResult.toolCalls.length > 0) {\n\t\t\t\tcapturedToolCalls = [...capturedToolCalls, ...stepResult.toolCalls];\n\t\t\t}\n\t\t\tif (stepResult.toolResults && stepResult.toolResults.length > 0) {\n\t\t\t\tcapturedToolResults = [...capturedToolResults, ...stepResult.toolResults];\n\t\t\t}\n\t\t};\n\t}\n\n\tconst response = await generateText(generateParams);\n\n\t// Handle cases where tool execution doesn't generate text\n\tlet responseText: string;\n\tif (\n\t\ttools &&\n\t\t(!response.text ||\n\t\t\tresponse.text.trim() === \"\" ||\n\t\t\tresponse.text === \"Tools executed successfully.\")\n\t) {\n\t\tresponseText = handleEmptyToolResponse(modelLabel);\n\t} else {\n\t\tresponseText = response.text;\n\t}\n\n\tif (response.usage) {\n\t\temitModelUsageEvent(runtime, modelType, prompt, response.usage);\n\t}\n\n\t// If tools were used, return the full response object to access toolCalls and toolResults\n\tif (\n\t\ttools &&\n\t\t(capturedToolCalls.length > 0 || capturedToolResults.length > 0)\n\t) {\n\t\treturn {\n\t\t\ttext: responseText,\n\t\t\ttoolCalls: capturedToolCalls,\n\t\t\ttoolResults: capturedToolResults,\n\t\t\t// Include other useful properties\n\t\t\tusage: response.usage,\n\t\t\tfinishReason: response.finishReason,\n\t\t};\n\t}\n\n\treturn responseText;\n}\n\n/**\n * TEXT_SMALL model handler\n */\nexport async function handleTextSmall(\n\truntime: IAgentRuntime,\n\tparams: GenerateTextParams & {\n\t\ttools?: Record<string, Tool>;\n\t\ttoolChoice?: ToolChoice<Record<string, Tool>>;\n\t},\n): Promise<string | ToolResponse> {\n\treturn generateTextWithModel(runtime, ModelType.TEXT_SMALL, params);\n}\n\n/**\n * TEXT_LARGE model handler\n */\nexport async function handleTextLarge(\n\truntime: IAgentRuntime,\n\tparams: GenerateTextParams & {\n\t\ttools?: Record<string, Tool>;\n\t\ttoolChoice?: ToolChoice<Record<string, Tool>>;\n\t},\n): Promise<string | ToolResponse> {\n\treturn generateTextWithModel(runtime, ModelType.TEXT_LARGE, params);\n}\n","import { createOpenRouter } from \"@openrouter/ai-sdk-provider\";\nimport { logger, type IAgentRuntime } from \"@elizaos/core\";\nimport { getApiKey } from \"../utils/config\";\n\n/**\n * Create an OpenRouter provider instance with proper configuration\n *\n * @param runtime The runtime context\n * @returns Configured OpenRouter provider instance\n */\nexport function createOpenRouterProvider(runtime: IAgentRuntime) {\n\tconst apiKey = getApiKey(runtime);\n\tif (!apiKey) {\n\t\t// This case should ideally be caught in init, but good practice to check\n\t\tlogger.error(\n\t\t\t\"OpenRouter API Key is missing when trying to create provider\",\n\t\t);\n\t\tthrow new Error(\"OpenRouter API Key is missing.\");\n\t}\n\n\t// Note: createOpenRouter doesn't seem to take baseURL directly in the documentation.\n\t// It might pick it up from OPENROUTER_BASE_URL env var automatically,\n\t// or it might not be needed/configurable in the same way as createOpenRouter.\n\t// We'll rely on the apiKey for now.\n\treturn createOpenRouter({\n\t\tapiKey: apiKey,\n\t\t// We might need to handle baseURL differently if required.\n\t\t// The @ai-sdk/provider utils might handle OPENROUTER_BASE_URL env var.\n\t});\n}\n","import {\n\tEventType,\n\ttype IAgentRuntime,\n\ttype ModelTypeName,\n} from \"@elizaos/core\";\nimport type { LanguageModelUsage } from \"ai\";\n\n/**\n * Emits a model usage event\n */\nexport function emitModelUsageEvent(\n\truntime: IAgentRuntime,\n\ttype: ModelTypeName,\n\tprompt: string,\n\tusage: LanguageModelUsage,\n) {\n\truntime.emitEvent(EventType.MODEL_USED, {\n\t\tprovider: \"openrouter\",\n\t\ttype,\n\t\tprompt,\n\t\ttokens: {\n\t\t\tprompt: usage.promptTokens,\n\t\t\tcompletion: usage.completionTokens,\n\t\t\ttotal: usage.totalTokens,\n\t\t},\n\t});\n}\n","import { logger } from \"@elizaos/core\";\nimport { JSONParseError } from \"ai\";\nimport type { GenerateTextResponse, ImageDescriptionResult } from \"../types\";\n\n/**\n * Returns a function to repair JSON text\n */\nexport function getJsonRepairFunction(): (params: {\n\ttext: string;\n\terror: unknown;\n}) => Promise<string | null> {\n\treturn async ({ text, error }: { text: string; error: unknown }) => {\n\t\ttry {\n\t\t\tif (error instanceof JSONParseError) {\n\t\t\t\tconst cleanedText = text.replace(/```json\\n|\\n```|```/g, \"\");\n\t\t\t\tJSON.parse(cleanedText);\n\t\t\t\treturn cleanedText;\n\t\t\t}\n\t\t\treturn null;\n\t\t} catch (jsonError: unknown) {\n\t\t\tconst message =\n\t\t\t\tjsonError instanceof Error ? jsonError.message : String(jsonError);\n\t\t\tlogger.warn(`Failed to repair JSON text: ${message}`);\n\t\t\treturn null;\n\t\t}\n\t};\n}\n\n// Re-export for backward compatibility\nexport { emitModelUsageEvent } from \"./events\";\n\n/**\n * Logs response structure for debugging (debug level only)\n */\nexport function logResponseStructure(\n\tmodelType: string,\n\tresponse: GenerateTextResponse,\n) {\n\tlogger.debug(`[${modelType}] Response structure:`, {\n\t\thasText: !!response.text,\n\t\ttextLength: response.text?.length || 0,\n\t\thasSteps: !!response.steps,\n\t\tstepsCount: response.steps?.length || 0,\n\t\tfinishReason: response.finishReason,\n\t\tusage: response.usage,\n\t});\n}\n\n/**\n * Handles cases where tool execution doesn't generate text\n */\nexport function handleEmptyToolResponse(modelType: string): string {\n\tlogger.warn(`[${modelType}] No text generated after tool execution`);\n\n\tconst fallbackText =\n\t\t\"I executed the requested action. The tool completed successfully.\";\n\tlogger.warn(`[${modelType}] Using fallback response text`);\n\treturn fallbackText;\n}\n\n/**\n * Parses image description response from text or JSON format\n */\nexport function parseImageDescriptionResponse(\n\tresponseText: string,\n): ImageDescriptionResult {\n\t// Try to parse as JSON first\n\ttry {\n\t\tconst jsonResponse = JSON.parse(responseText);\n\t\tif (jsonResponse.title && jsonResponse.description) {\n\t\t\treturn jsonResponse;\n\t\t}\n\t} catch (e) {\n\t\t// If not valid JSON, process as text\n\t\tlogger.debug(`Parsing as JSON failed, processing as text: ${e}`);\n\t}\n\n\t// Extract title and description from text format\n\tconst titleMatch = responseText.match(/title[:\\s]+(.+?)(?:\\n|$)/i);\n\tconst title = titleMatch?.[1]?.trim() || \"Image Analysis\";\n\tconst description = responseText\n\t\t.replace(/title[:\\s]+(.+?)(?:\\n|$)/i, \"\")\n\t\t.trim();\n\n\treturn { title, description };\n}\n\n/**\n * Handles errors during object generation, including JSON repair attempts\n */\nexport async function handleObjectGenerationError(\n\terror: unknown,\n): Promise<unknown> {\n\tif (error instanceof JSONParseError) {\n\t\tlogger.error(`[generateObject] Failed to parse JSON: ${error.message}`);\n\t\tconst repairFunction = getJsonRepairFunction();\n\t\tconst repairedJsonString = await repairFunction({\n\t\t\ttext: error.text,\n\t\t\terror,\n\t\t});\n\n\t\tif (repairedJsonString) {\n\t\t\ttry {\n\t\t\t\tconst repairedObject = JSON.parse(repairedJsonString);\n\t\t\t\tlogger.log(\"[generateObject] Successfully repaired JSON.\");\n\t\t\t\treturn repairedObject;\n\t\t\t} catch (repairParseError: unknown) {\n\t\t\t\tconst message =\n\t\t\t\t\trepairParseError instanceof Error\n\t\t\t\t\t\t? repairParseError.message\n\t\t\t\t\t\t: String(repairParseError);\n\t\t\t\tlogger.error(\n\t\t\t\t\t`[generateObject] Failed to parse repaired JSON: ${message}`,\n\t\t\t\t);\n\t\t\t\tif (repairParseError instanceof Error) throw repairParseError;\n\t\t\t\tthrow Object.assign(new Error(message), { cause: repairParseError });\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.error(\"[generateObject] JSON repair failed.\");\n\t\t\tthrow error;\n\t\t}\n\t} else {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tlogger.error(`[generateObject] Unknown error: ${message}`);\n\t\tif (error instanceof Error) throw error;\n\t\tthrow Object.assign(new Error(message), { cause: error });\n\t}\n}\n","import {\n\tModelType,\n\tlogger,\n\ttype IAgentRuntime,\n\ttype ObjectGenerationParams,\n} from \"@elizaos/core\";\nimport { generateObject } from \"ai\";\nimport { createOpenRouterProvider } from \"../providers\";\nimport { getSmallModel, getLargeModel } from \"../utils/config\";\nimport { emitModelUsageEvent } from \"../utils/events\";\nimport {\n\tgetJsonRepairFunction,\n\thandleObjectGenerationError,\n} from \"../utils/helpers\";\n\n/**\n * Common object generation logic for both small and large models\n */\nasync function generateObjectWithModel(\n\truntime: IAgentRuntime,\n\tmodelType: typeof ModelType.OBJECT_SMALL | typeof ModelType.OBJECT_LARGE,\n\tparams: ObjectGenerationParams,\n): Promise<unknown> {\n\tconst openrouter = createOpenRouterProvider(runtime);\n\tconst modelName =\n\t\tmodelType === ModelType.OBJECT_SMALL\n\t\t\t? getSmallModel(runtime)\n\t\t\t: getLargeModel(runtime);\n\tconst modelLabel =\n\t\tmodelType === ModelType.OBJECT_SMALL ? \"OBJECT_SMALL\" : \"OBJECT_LARGE\";\n\n\tlogger.log(`[OpenRouter] Using ${modelLabel} model: ${modelName}`);\n\tconst temperature = params.temperature ?? 0.7;\n\n\ttry {\n\t\tconst { object, usage } = await generateObject({\n\t\t\tmodel: openrouter.chat(modelName),\n\t\t\toutput: \"no-schema\",\n\t\t\tprompt: params.prompt,\n\t\t\ttemperature: temperature,\n\t\t\texperimental_repairText: getJsonRepairFunction(),\n\t\t});\n\n\t\tif (usage) {\n\t\t\temitModelUsageEvent(runtime, modelType, params.prompt, usage);\n\t\t}\n\t\treturn object;\n\t} catch (error: unknown) {\n\t\treturn handleObjectGenerationError(error);\n\t}\n}\n\n/**\n * OBJECT_SMALL model handler\n */\nexport async function handleObjectSmall(\n\truntime: IAgentRuntime,\n\tparams: ObjectGenerationParams,\n): Promise<unknown> {\n\treturn generateObjectWithModel(runtime, ModelType.OBJECT_SMALL, params);\n}\n\n/**\n * OBJECT_LARGE model handler\n */\nexport async function handleObjectLarge(\n\truntime: IAgentRuntime,\n\tparams: ObjectGenerationParams,\n): Promise<unknown> {\n\treturn generateObjectWithModel(runtime, ModelType.OBJECT_LARGE, params);\n}\n","import {\n\tlogger,\n\ttype IAgentRuntime,\n\ttype ImageDescriptionParams,\n} from \"@elizaos/core\";\nimport { generateText } from \"ai\";\nimport { createOpenRouterProvider } from \"../providers\";\nimport { getImageModel } from \"../utils/config\";\nimport { parseImageDescriptionResponse } from \"../utils/helpers\";\n\n/**\n * IMAGE_DESCRIPTION model handler\n */\nexport async function handleImageDescription(\n\truntime: IAgentRuntime,\n\tparams: ImageDescriptionParams | string,\n): Promise<{ title: string; description: string }> {\n\tlet imageUrl: string;\n\tlet promptText: string | undefined;\n\tconst modelName = getImageModel(runtime);\n\tlogger.log(`[OpenRouter] Using IMAGE_DESCRIPTION model: ${modelName}`);\n\tconst maxTokens = 300;\n\n\tif (typeof params === \"string\") {\n\t\timageUrl = params;\n\t\tpromptText =\n\t\t\t\"Please analyze this image and provide a title and detailed description.\";\n\t} else {\n\t\timageUrl = params.imageUrl;\n\t\tpromptText =\n\t\t\tparams.prompt ||\n\t\t\t\"Please analyze this image and provide a title and detailed description.\";\n\t}\n\n\tconst openrouter = createOpenRouterProvider(runtime);\n\n\tconst messages = [\n\t\t{\n\t\t\trole: \"user\" as const,\n\t\t\tcontent: [\n\t\t\t\t{ type: \"text\" as const, text: promptText },\n\t\t\t\t{ type: \"image\" as const, image: imageUrl },\n\t\t\t],\n\t\t},\n\t];\n\n\ttry {\n\t\tconst model = openrouter.chat(modelName);\n\n\t\tconst { text: responseText } = await generateText({\n\t\t\tmodel: model,\n\t\t\tmessages: messages,\n\t\t\tmaxTokens: maxTokens,\n\t\t});\n\n\t\treturn parseImageDescriptionResponse(responseText);\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tlogger.error(`Error analyzing image: ${message}`);\n\t\treturn {\n\t\t\ttitle: \"Failed to analyze image\",\n\t\t\tdescription: `Error: ${message}`,\n\t\t};\n\t}\n}\n"],"mappings":";AAAA;AAAA,EACC,aAAAA;AAAA,OAMM;;;ACPP,SAAS,cAAkC;AAC3C,SA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ger","logger","ModelType","logger","ModelType","logger","logger","generateText","logger","generateText","ModelType"]}
package/package.json CHANGED
@@ -1,112 +1,112 @@
1
1
  {
2
- "name": "@elizaos/plugin-openrouter",
3
- "version": "1.2.5",
4
- "type": "module",
5
- "main": "dist/index.js",
6
- "module": "dist/index.js",
7
- "types": "dist/index.d.ts",
8
- "repository": {
9
- "type": "git",
10
- "url": "git+https://github.com/elizaos-plugins/plugin-openrouter.git"
11
- },
12
- "exports": {
13
- "./package.json": "./package.json",
14
- ".": {
15
- "import": {
16
- "types": "./dist/index.d.ts",
17
- "default": "./dist/index.js"
18
- }
19
- }
20
- },
21
- "files": [
22
- "dist"
23
- ],
24
- "dependencies": {
25
- "@ai-sdk/openai": "^1.3.22",
26
- "@ai-sdk/ui-utils": "1.2.11",
27
- "@elizaos/core": "^1.2.5",
28
- "@openrouter/ai-sdk-provider": "^0.4.5",
29
- "ai": "^4.3.15",
30
- "undici": "^7.9.0"
31
- },
32
- "devDependencies": {
33
- "@types/node": "^20.0.0",
34
- "prettier": "3.5.3",
35
- "tsup": "8.4.0",
36
- "typescript": "5.8.3",
37
- "vitest": "3.1.3",
38
- "dotenv": "^16.5.0"
39
- },
40
- "scripts": {
41
- "build": "tsup",
42
- "dev": "tsup --watch",
43
- "lint": "prettier --write ./src",
44
- "clean": "rm -rf dist .turbo node_modules .turbo-tsconfig.json tsconfig.tsbuildinfo",
45
- "format": "prettier --write ./src",
46
- "format:check": "prettier --check ./src",
47
- "test": "vitest run",
48
- "test:watch": "vitest"
49
- },
50
- "publishConfig": {
51
- "access": "public"
52
- },
53
- "agentConfig": {
54
- "pluginType": "elizaos:plugin:1.0.0",
55
- "pluginParameters": {
56
- "OPENROUTER_API_KEY": {
57
- "type": "string",
58
- "description": "API key used by the OpenRouter plugin for authenticating requests.",
59
- "required": true,
60
- "sensitive": true
61
- },
62
- "OPENROUTER_IMAGE_MODEL": {
63
- "type": "string",
64
- "description": "Overrides the default image description model used by the OpenRouter plugin.",
65
- "required": false,
66
- "sensitive": false
67
- },
68
- "OPENROUTER_BASE_URL": {
69
- "type": "string",
70
- "description": "Base URL for the OpenRouter API endpoints.",
71
- "required": false,
72
- "default": "https://openrouter.ai/api/v1",
73
- "sensitive": false
74
- },
75
- "OPENROUTER_SMALL_MODEL": {
76
- "type": "string",
77
- "description": "Overrides the default small language model used for text/object generation.",
78
- "required": false,
79
- "default": "google/gemini-2.0-flash-001",
80
- "sensitive": false
81
- },
82
- "OPENROUTER_LARGE_MODEL": {
83
- "type": "string",
84
- "description": "Overrides the default large language model used for text/object generation.",
85
- "required": false,
86
- "default": "google/gemini-2.5-flash-preview-05-20",
87
- "sensitive": false
88
- },
89
- "SMALL_MODEL": {
90
- "type": "string",
91
- "description": "General fallback environment variable for the small model name when OPENROUTER_SMALL_MODEL is not set.",
92
- "required": false,
93
- "default": "google/gemini-2.0-flash-001",
94
- "sensitive": false
95
- },
96
- "LARGE_MODEL": {
97
- "type": "string",
98
- "description": "General fallback environment variable for the large model name when OPENROUTER_LARGE_MODEL is not set.",
99
- "required": false,
100
- "default": "google/gemini-2.5-flash-preview-05-20",
101
- "sensitive": false
102
- },
103
- "IMAGE_MODEL": {
104
- "type": "string",
105
- "description": "General fallback environment variable for the image model name when OPENROUTER_IMAGE_MODEL is not set.",
106
- "required": false,
107
- "default": "x-ai/grok-2-vision-1212",
108
- "sensitive": false
109
- }
110
- }
111
- }
2
+ "name": "@elizaos/plugin-openrouter",
3
+ "version": "1.2.6",
4
+ "type": "module",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/elizaos-plugins/plugin-openrouter.git"
11
+ },
12
+ "exports": {
13
+ "./package.json": "./package.json",
14
+ ".": {
15
+ "import": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ }
19
+ }
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "dependencies": {
25
+ "@ai-sdk/openai": "^1.3.22",
26
+ "@ai-sdk/ui-utils": "1.2.11",
27
+ "@elizaos/core": "^1.2.5",
28
+ "@openrouter/ai-sdk-provider": "^0.4.5",
29
+ "ai": "^4.3.15",
30
+ "undici": "^7.9.0"
31
+ },
32
+ "devDependencies": {
33
+ "@types/bun": "^1.1.14",
34
+ "@types/node": "^20.0.0",
35
+ "prettier": "3.5.3",
36
+ "tsup": "8.4.0",
37
+ "typescript": "5.8.3",
38
+ "dotenv": "^16.5.0"
39
+ },
40
+ "scripts": {
41
+ "build": "tsup",
42
+ "dev": "tsup --watch",
43
+ "lint": "prettier --write ./src",
44
+ "clean": "rm -rf dist .turbo node_modules .turbo-tsconfig.json tsconfig.tsbuildinfo",
45
+ "format": "prettier --write ./src",
46
+ "format:check": "prettier --check ./src",
47
+ "test": "bun test",
48
+ "test:watch": "bun test --watch"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ },
53
+ "agentConfig": {
54
+ "pluginType": "elizaos:plugin:1.0.0",
55
+ "pluginParameters": {
56
+ "OPENROUTER_API_KEY": {
57
+ "type": "string",
58
+ "description": "API key used by the OpenRouter plugin for authenticating requests.",
59
+ "required": true,
60
+ "sensitive": true
61
+ },
62
+ "OPENROUTER_IMAGE_MODEL": {
63
+ "type": "string",
64
+ "description": "Overrides the default image description model used by the OpenRouter plugin.",
65
+ "required": false,
66
+ "sensitive": false
67
+ },
68
+ "OPENROUTER_BASE_URL": {
69
+ "type": "string",
70
+ "description": "Base URL for the OpenRouter API endpoints.",
71
+ "required": false,
72
+ "default": "https://openrouter.ai/api/v1",
73
+ "sensitive": false
74
+ },
75
+ "OPENROUTER_SMALL_MODEL": {
76
+ "type": "string",
77
+ "description": "Overrides the default small language model used for text/object generation.",
78
+ "required": false,
79
+ "default": "google/gemini-2.0-flash-001",
80
+ "sensitive": false
81
+ },
82
+ "OPENROUTER_LARGE_MODEL": {
83
+ "type": "string",
84
+ "description": "Overrides the default large language model used for text/object generation.",
85
+ "required": false,
86
+ "default": "google/gemini-2.5-flash-preview-05-20",
87
+ "sensitive": false
88
+ },
89
+ "SMALL_MODEL": {
90
+ "type": "string",
91
+ "description": "General fallback environment variable for the small model name when OPENROUTER_SMALL_MODEL is not set.",
92
+ "required": false,
93
+ "default": "google/gemini-2.0-flash-001",
94
+ "sensitive": false
95
+ },
96
+ "LARGE_MODEL": {
97
+ "type": "string",
98
+ "description": "General fallback environment variable for the large model name when OPENROUTER_LARGE_MODEL is not set.",
99
+ "required": false,
100
+ "default": "google/gemini-2.5-flash-preview-05-20",
101
+ "sensitive": false
102
+ },
103
+ "IMAGE_MODEL": {
104
+ "type": "string",
105
+ "description": "General fallback environment variable for the image model name when OPENROUTER_IMAGE_MODEL is not set.",
106
+ "required": false,
107
+ "default": "x-ai/grok-2-vision-1212",
108
+ "sensitive": false
109
+ }
110
+ }
111
+ }
112
112
  }