@elizaos/plugin-openrouter 1.0.0-beta.51
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/LICENSE +21 -0
- package/README.md +69 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +355 -0
- package/dist/index.js.map +1 -0
- package/package.json +61 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Shaw Walters and elizaOS Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# @elizaos/plugin-openrouter
|
|
2
|
+
|
|
3
|
+
This plugin provides integration with various models available through the OpenRouter API via the ElizaOS platform.
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
Add the plugin to your character configuration:
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
"plugins": ["@elizaos/plugin-openrouter"]
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Configuration
|
|
14
|
+
|
|
15
|
+
The plugin requires the OpenRouter API key and can be configured via environment variables or character settings.
|
|
16
|
+
|
|
17
|
+
**Character Settings Example:**
|
|
18
|
+
|
|
19
|
+
```json
|
|
20
|
+
"settings": {
|
|
21
|
+
"OPENROUTER_API_KEY": "your_openrouter_api_key",
|
|
22
|
+
"OPENROUTER_BASE_URL": "https://openrouter.ai/api/v1", // Optional: Default is OpenRouter endpoint
|
|
23
|
+
"OPENROUTER_SMALL_MODEL": "google/gemini-flash", // Optional: Overrides default small model
|
|
24
|
+
"OPENROUTER_LARGE_MODEL": "google/gemini-pro", // Optional: Overrides default large model
|
|
25
|
+
"OPENROUTER_IMAGE_MODEL": "x-ai/grok-2-vision-1212", // Optional: Overrides default image model
|
|
26
|
+
// Fallbacks if specific OPENROUTER models are not set
|
|
27
|
+
"SMALL_MODEL": "google/gemini-flash",
|
|
28
|
+
"LARGE_MODEL": "google/gemini-pro",
|
|
29
|
+
"IMAGE_MODEL": "x-ai/grok-2-vision-1212"
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
**`.env` File Example:**
|
|
34
|
+
|
|
35
|
+
```
|
|
36
|
+
OPENROUTER_API_KEY=your_openrouter_api_key
|
|
37
|
+
# Optional overrides:
|
|
38
|
+
OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
|
|
39
|
+
OPENROUTER_SMALL_MODEL=google/gemini-flash
|
|
40
|
+
OPENROUTER_LARGE_MODEL=google/gemini-pro
|
|
41
|
+
OPENROUTER_IMAGE_MODEL=x-ai/grok-2-vision-1212
|
|
42
|
+
# Fallbacks if specific OPENROUTER models are not set
|
|
43
|
+
SMALL_MODEL=google/gemini-flash
|
|
44
|
+
LARGE_MODEL=google/gemini-pro
|
|
45
|
+
IMAGE_MODEL=x-ai/grok-2-vision-1212
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Configuration Options
|
|
49
|
+
|
|
50
|
+
- `OPENROUTER_API_KEY` (required): Your OpenRouter API key.
|
|
51
|
+
- `OPENROUTER_BASE_URL`: Custom API endpoint (default: https://openrouter.ai/api/v1).
|
|
52
|
+
- `OPENROUTER_SMALL_MODEL`: Specific model to use for `TEXT_SMALL` and `OBJECT_SMALL`. Overrides `SMALL_MODEL` if set.
|
|
53
|
+
- `OPENROUTER_LARGE_MODEL`: Specific model to use for `TEXT_LARGE` and `OBJECT_LARGE`. Overrides `LARGE_MODEL` if set.
|
|
54
|
+
- `OPENROUTER_IMAGE_MODEL`: Specific model to use for `IMAGE_DESCRIPTION`. Overrides `IMAGE_MODEL` if set.
|
|
55
|
+
- `SMALL_MODEL`: Fallback model for small tasks (default: "google/gemini-flash"). Used if `OPENROUTER_SMALL_MODEL` is not set.
|
|
56
|
+
- `LARGE_MODEL`: Fallback model for large tasks (default: "google/gemini-pro"). Used if `OPENROUTER_LARGE_MODEL` is not set.
|
|
57
|
+
- `IMAGE_MODEL`: Fallback model for image analysis (default: "x-ai/grok-2-vision-1212"). Used if `OPENROUTER_IMAGE_MODEL` is not set.
|
|
58
|
+
|
|
59
|
+
## Provided Models
|
|
60
|
+
|
|
61
|
+
The plugin currently provides these model types:
|
|
62
|
+
|
|
63
|
+
- `TEXT_SMALL`: Optimized for fast, cost-effective text generation using the configured small model.
|
|
64
|
+
- `TEXT_LARGE`: For more complex text generation tasks requiring larger models, using the configured large model.
|
|
65
|
+
- `OBJECT_SMALL`: Generates structured JSON objects based on a prompt, using the configured small model.
|
|
66
|
+
- `OBJECT_LARGE`: Generates structured JSON objects based on a prompt, using the configured large model.
|
|
67
|
+
- `IMAGE_DESCRIPTION`: Analyzes images and provides descriptive text and titles, using the configured image model.
|
|
68
|
+
|
|
69
|
+
_Note: Features like Image Generation, Audio Transcription, and Embeddings are not currently implemented in this specific OpenRouter plugin._
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { createOpenRouter } from "@openrouter/ai-sdk-provider";
|
|
3
|
+
import { getProviderBaseURL } from "@elizaos/core";
|
|
4
|
+
import { EventType, logger, ModelType, safeReplacer } from "@elizaos/core";
|
|
5
|
+
import {
|
|
6
|
+
generateObject,
|
|
7
|
+
generateText,
|
|
8
|
+
JSONParseError
|
|
9
|
+
} from "ai";
|
|
10
|
+
import { fetch } from "undici";
|
|
11
|
+
function getSetting(runtime, key, defaultValue) {
|
|
12
|
+
return runtime.getSetting(key) ?? process.env[key] ?? defaultValue;
|
|
13
|
+
}
|
|
14
|
+
function getBaseURL(runtime) {
|
|
15
|
+
const defaultBaseURL = getSetting(
|
|
16
|
+
runtime,
|
|
17
|
+
"OPENROUTER_BASE_URL",
|
|
18
|
+
"https://openrouter.ai/api/v1"
|
|
19
|
+
);
|
|
20
|
+
const providerBaseURL = getProviderBaseURL(
|
|
21
|
+
runtime,
|
|
22
|
+
"openrouter",
|
|
23
|
+
defaultBaseURL
|
|
24
|
+
);
|
|
25
|
+
return providerBaseURL || defaultBaseURL;
|
|
26
|
+
}
|
|
27
|
+
function getApiKey(runtime) {
|
|
28
|
+
return getSetting(runtime, "OPENROUTER_API_KEY");
|
|
29
|
+
}
|
|
30
|
+
function getSmallModel(runtime) {
|
|
31
|
+
return getSetting(runtime, "OPENROUTER_SMALL_MODEL") ?? getSetting(runtime, "SMALL_MODEL", "google/gemini-flash") ?? "google/gemini-flash";
|
|
32
|
+
}
|
|
33
|
+
function getLargeModel(runtime) {
|
|
34
|
+
return getSetting(runtime, "OPENROUTER_LARGE_MODEL") ?? getSetting(runtime, "LARGE_MODEL", "google/gemini-pro") ?? "google/gemini-pro";
|
|
35
|
+
}
|
|
36
|
+
function getImageModel(runtime) {
|
|
37
|
+
return getSetting(runtime, "OPENROUTER_IMAGE_MODEL") ?? getSetting(runtime, "IMAGE_MODEL", "x-ai/grok-2-vision-1212") ?? "x-ai/grok-2-vision-1212";
|
|
38
|
+
}
|
|
39
|
+
function createOpenRouterProvider(runtime) {
|
|
40
|
+
const apiKey = getApiKey(runtime);
|
|
41
|
+
if (!apiKey) {
|
|
42
|
+
logger.error(
|
|
43
|
+
"OpenRouter API Key is missing when trying to create provider"
|
|
44
|
+
);
|
|
45
|
+
throw new Error("OpenRouter API Key is missing.");
|
|
46
|
+
}
|
|
47
|
+
return createOpenRouter({
|
|
48
|
+
apiKey
|
|
49
|
+
// We might need to handle baseURL differently if required.
|
|
50
|
+
// The @ai-sdk/provider utils might handle OPENROUTER_BASE_URL env var.
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
async function generateObjectByModelType(runtime, params, modelType, getModelFn) {
|
|
54
|
+
const openrouter = createOpenRouterProvider(runtime);
|
|
55
|
+
const modelName = getModelFn(runtime);
|
|
56
|
+
const temperature = params.temperature ?? 0;
|
|
57
|
+
const schemaPresent = !!params.schema;
|
|
58
|
+
if (schemaPresent) {
|
|
59
|
+
logger.info(
|
|
60
|
+
`Using ${modelType} without schema validation (schema provided but output=no-schema)`
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
const { object, usage } = await generateObject({
|
|
65
|
+
model: openrouter.chat(modelName),
|
|
66
|
+
output: "no-schema",
|
|
67
|
+
prompt: params.prompt,
|
|
68
|
+
temperature,
|
|
69
|
+
experimental_repairText: getJsonRepairFunction()
|
|
70
|
+
});
|
|
71
|
+
if (usage) {
|
|
72
|
+
emitModelUsageEvent(
|
|
73
|
+
runtime,
|
|
74
|
+
modelType,
|
|
75
|
+
params.prompt,
|
|
76
|
+
usage
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
return object;
|
|
80
|
+
} catch (error) {
|
|
81
|
+
if (error instanceof JSONParseError) {
|
|
82
|
+
logger.error(`[generateObject] Failed to parse JSON: ${error.message}`);
|
|
83
|
+
const repairFunction = getJsonRepairFunction();
|
|
84
|
+
const repairedJsonString = await repairFunction({
|
|
85
|
+
text: error.text,
|
|
86
|
+
error
|
|
87
|
+
});
|
|
88
|
+
if (repairedJsonString) {
|
|
89
|
+
try {
|
|
90
|
+
const repairedObject = JSON.parse(repairedJsonString);
|
|
91
|
+
logger.info("[generateObject] Successfully repaired JSON.");
|
|
92
|
+
return repairedObject;
|
|
93
|
+
} catch (repairParseError) {
|
|
94
|
+
const message = repairParseError instanceof Error ? repairParseError.message : String(repairParseError);
|
|
95
|
+
logger.error(
|
|
96
|
+
`[generateObject] Failed to parse repaired JSON: ${message}`
|
|
97
|
+
);
|
|
98
|
+
const exception = repairParseError instanceof Error ? repairParseError : new Error(message);
|
|
99
|
+
throw exception;
|
|
100
|
+
}
|
|
101
|
+
} else {
|
|
102
|
+
const errMsg = error instanceof Error ? error.message : String(error);
|
|
103
|
+
logger.error("[generateObject] JSON repair failed.");
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
} else {
|
|
107
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
108
|
+
logger.error(`[generateObject] Unknown error: ${message}`);
|
|
109
|
+
const exception = error instanceof Error ? error : new Error(message);
|
|
110
|
+
throw exception;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function getJsonRepairFunction() {
|
|
115
|
+
return async ({ text, error }) => {
|
|
116
|
+
try {
|
|
117
|
+
if (error instanceof JSONParseError) {
|
|
118
|
+
const cleanedText = text.replace(/```json\n|\n```|```/g, "");
|
|
119
|
+
JSON.parse(cleanedText);
|
|
120
|
+
return cleanedText;
|
|
121
|
+
}
|
|
122
|
+
return null;
|
|
123
|
+
} catch (jsonError) {
|
|
124
|
+
const message = jsonError instanceof Error ? jsonError.message : String(jsonError);
|
|
125
|
+
logger.warn(`Failed to repair JSON text: ${message}`);
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
function emitModelUsageEvent(runtime, type, prompt, usage) {
|
|
131
|
+
runtime.emitEvent(EventType.MODEL_USED, {
|
|
132
|
+
provider: "openrouter",
|
|
133
|
+
type,
|
|
134
|
+
prompt,
|
|
135
|
+
tokens: {
|
|
136
|
+
prompt: usage.promptTokens,
|
|
137
|
+
completion: usage.completionTokens,
|
|
138
|
+
total: usage.totalTokens
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
var openrouterPlugin = {
|
|
143
|
+
name: "openrouter",
|
|
144
|
+
description: "OpenAI plugin",
|
|
145
|
+
config: {
|
|
146
|
+
OPENROUTER_API_KEY: process.env.OPENROUTER_API_KEY,
|
|
147
|
+
OPENROUTER_BASE_URL: process.env.OPENROUTER_BASE_URL,
|
|
148
|
+
OPENROUTER_SMALL_MODEL: process.env.OPENROUTER_SMALL_MODEL,
|
|
149
|
+
OPENROUTER_LARGE_MODEL: process.env.OPENROUTER_LARGE_MODEL,
|
|
150
|
+
OPENROUTER_IMAGE_MODEL: process.env.OPENROUTER_IMAGE_MODEL,
|
|
151
|
+
SMALL_MODEL: process.env.SMALL_MODEL,
|
|
152
|
+
LARGE_MODEL: process.env.LARGE_MODEL,
|
|
153
|
+
IMAGE_MODEL: process.env.IMAGE_MODEL
|
|
154
|
+
},
|
|
155
|
+
async init(_config, runtime) {
|
|
156
|
+
try {
|
|
157
|
+
if (!getApiKey(runtime)) {
|
|
158
|
+
logger.warn(
|
|
159
|
+
"OPENROUTER_API_KEY is not set in environment - OpenAI functionality will be limited"
|
|
160
|
+
);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
const baseURL = getBaseURL(runtime);
|
|
165
|
+
const response = await fetch(`${baseURL}/models`, {
|
|
166
|
+
headers: { Authorization: `Bearer ${getApiKey(runtime)}` }
|
|
167
|
+
});
|
|
168
|
+
if (!response.ok) {
|
|
169
|
+
logger.warn(
|
|
170
|
+
`OpenAI API key validation failed: ${response.statusText}`
|
|
171
|
+
);
|
|
172
|
+
logger.warn(
|
|
173
|
+
"OpenAI functionality will be limited until a valid API key is provided"
|
|
174
|
+
);
|
|
175
|
+
} else {
|
|
176
|
+
logger.log("OpenAI API key validated successfully");
|
|
177
|
+
}
|
|
178
|
+
} catch (fetchError) {
|
|
179
|
+
const message = fetchError instanceof Error ? fetchError.message : String(fetchError);
|
|
180
|
+
logger.warn(`Error validating OpenAI API key: ${message}`);
|
|
181
|
+
logger.warn(
|
|
182
|
+
"OpenAI functionality will be limited until a valid API key is provided"
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
} catch (error) {
|
|
186
|
+
const message = error?.errors?.map((e) => e.message).join(", ") || (error instanceof Error ? error.message : String(error));
|
|
187
|
+
logger.warn(
|
|
188
|
+
`OpenAI plugin configuration issue: ${message} - You need to configure the OPENROUTER_API_KEY in your environment variables`
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
models: {
|
|
193
|
+
[ModelType.TEXT_SMALL]: async (runtime, { prompt, stopSequences = [] }) => {
|
|
194
|
+
const temperature = 0.7;
|
|
195
|
+
const frequency_penalty = 0.7;
|
|
196
|
+
const presence_penalty = 0.7;
|
|
197
|
+
const max_response_length = 8192;
|
|
198
|
+
const openrouter = createOpenRouterProvider(runtime);
|
|
199
|
+
const modelName = getSmallModel(runtime);
|
|
200
|
+
logger.log("generating text");
|
|
201
|
+
logger.log(prompt);
|
|
202
|
+
let responseText = "";
|
|
203
|
+
let usage;
|
|
204
|
+
const model = openrouter.chat(modelName);
|
|
205
|
+
const system = runtime.character.system ?? void 0;
|
|
206
|
+
const callParams = {
|
|
207
|
+
model: modelName,
|
|
208
|
+
prompt,
|
|
209
|
+
system,
|
|
210
|
+
temperature,
|
|
211
|
+
maxTokens: max_response_length,
|
|
212
|
+
frequencyPenalty: frequency_penalty,
|
|
213
|
+
presencePenalty: presence_penalty,
|
|
214
|
+
stopSequences
|
|
215
|
+
};
|
|
216
|
+
logger.debug(
|
|
217
|
+
`[TEXT_SMALL] Calling generateText with params: ${JSON.stringify(callParams, safeReplacer())}`
|
|
218
|
+
);
|
|
219
|
+
try {
|
|
220
|
+
const { text, usage: usageData } = await generateText({
|
|
221
|
+
model,
|
|
222
|
+
prompt,
|
|
223
|
+
system,
|
|
224
|
+
temperature,
|
|
225
|
+
maxTokens: max_response_length,
|
|
226
|
+
frequencyPenalty: frequency_penalty,
|
|
227
|
+
presencePenalty: presence_penalty,
|
|
228
|
+
stopSequences
|
|
229
|
+
});
|
|
230
|
+
responseText = text;
|
|
231
|
+
usage = usageData;
|
|
232
|
+
} catch (e) {
|
|
233
|
+
logger.error(
|
|
234
|
+
`[TEXT_SMALL] Error during generateText call: ${JSON.stringify(e, Object.getOwnPropertyNames(e), 2)}`
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
if (usage) {
|
|
238
|
+
emitModelUsageEvent(runtime, ModelType.TEXT_SMALL, prompt, usage);
|
|
239
|
+
}
|
|
240
|
+
return responseText;
|
|
241
|
+
},
|
|
242
|
+
[ModelType.TEXT_LARGE]: async (runtime, {
|
|
243
|
+
prompt,
|
|
244
|
+
stopSequences = [],
|
|
245
|
+
maxTokens = 8192,
|
|
246
|
+
temperature = 0.7,
|
|
247
|
+
frequencyPenalty = 0.7,
|
|
248
|
+
presencePenalty = 0.7
|
|
249
|
+
}) => {
|
|
250
|
+
const openrouter = createOpenRouterProvider(runtime);
|
|
251
|
+
const modelName = getLargeModel(runtime);
|
|
252
|
+
logger.log("generating text");
|
|
253
|
+
logger.log(prompt);
|
|
254
|
+
let responseText = "";
|
|
255
|
+
let usage;
|
|
256
|
+
try {
|
|
257
|
+
const { text, usage: usageData } = await generateText({
|
|
258
|
+
model: openrouter.chat(modelName),
|
|
259
|
+
prompt,
|
|
260
|
+
system: runtime.character.system ?? void 0,
|
|
261
|
+
temperature,
|
|
262
|
+
maxTokens,
|
|
263
|
+
frequencyPenalty,
|
|
264
|
+
presencePenalty,
|
|
265
|
+
stopSequences
|
|
266
|
+
});
|
|
267
|
+
responseText = text;
|
|
268
|
+
usage = usageData;
|
|
269
|
+
} catch (e) {
|
|
270
|
+
logger.error(
|
|
271
|
+
`[TEXT_LARGE] Error during generateText call: ${JSON.stringify(e, Object.getOwnPropertyNames(e), 2)}`
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
if (usage) {
|
|
275
|
+
emitModelUsageEvent(runtime, ModelType.TEXT_LARGE, prompt, usage);
|
|
276
|
+
}
|
|
277
|
+
return responseText;
|
|
278
|
+
},
|
|
279
|
+
[ModelType.OBJECT_SMALL]: async (runtime, params) => {
|
|
280
|
+
return generateObjectByModelType(
|
|
281
|
+
runtime,
|
|
282
|
+
params,
|
|
283
|
+
ModelType.OBJECT_SMALL,
|
|
284
|
+
getSmallModel
|
|
285
|
+
);
|
|
286
|
+
},
|
|
287
|
+
[ModelType.OBJECT_LARGE]: async (runtime, params) => {
|
|
288
|
+
return generateObjectByModelType(
|
|
289
|
+
runtime,
|
|
290
|
+
params,
|
|
291
|
+
ModelType.OBJECT_LARGE,
|
|
292
|
+
getLargeModel
|
|
293
|
+
);
|
|
294
|
+
},
|
|
295
|
+
[ModelType.IMAGE_DESCRIPTION]: async (runtime, params) => {
|
|
296
|
+
let imageUrl;
|
|
297
|
+
let promptText;
|
|
298
|
+
const modelName = getImageModel(runtime);
|
|
299
|
+
logger.log(`[OpenRouter] Using IMAGE_DESCRIPTION model: ${modelName}`);
|
|
300
|
+
const maxTokens = 300;
|
|
301
|
+
if (typeof params === "string") {
|
|
302
|
+
imageUrl = params;
|
|
303
|
+
promptText = "Please analyze this image and provide a title and detailed description.";
|
|
304
|
+
} else {
|
|
305
|
+
imageUrl = params.imageUrl;
|
|
306
|
+
promptText = params.prompt || "Please analyze this image and provide a title and detailed description.";
|
|
307
|
+
}
|
|
308
|
+
const openrouter = createOpenRouterProvider(runtime);
|
|
309
|
+
const messages = [
|
|
310
|
+
{
|
|
311
|
+
role: "user",
|
|
312
|
+
content: [
|
|
313
|
+
{ type: "text", text: promptText },
|
|
314
|
+
{ type: "image_url", image_url: { url: imageUrl } }
|
|
315
|
+
]
|
|
316
|
+
}
|
|
317
|
+
];
|
|
318
|
+
try {
|
|
319
|
+
logger.log("Sending image description request to OpenRouter");
|
|
320
|
+
const model = openrouter.chat(modelName);
|
|
321
|
+
const { text: responseText } = await generateText({
|
|
322
|
+
model,
|
|
323
|
+
prompt: JSON.stringify(messages),
|
|
324
|
+
maxTokens
|
|
325
|
+
});
|
|
326
|
+
logger.log("Received response for image description");
|
|
327
|
+
try {
|
|
328
|
+
const jsonResponse = JSON.parse(responseText);
|
|
329
|
+
if (jsonResponse.title && jsonResponse.description) {
|
|
330
|
+
return jsonResponse;
|
|
331
|
+
}
|
|
332
|
+
} catch (e) {
|
|
333
|
+
logger.debug(`Parsing as JSON failed, processing as text: ${e}`);
|
|
334
|
+
}
|
|
335
|
+
const titleMatch = responseText.match(/title[:\s]+(.+?)(?:\n|$)/i);
|
|
336
|
+
const title = titleMatch?.[1]?.trim() || "Image Analysis";
|
|
337
|
+
const description = responseText.replace(/title[:\s]+(.+?)(?:\n|$)/i, "").trim();
|
|
338
|
+
return { title, description };
|
|
339
|
+
} catch (error) {
|
|
340
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
341
|
+
logger.error(`Error analyzing image: ${message}`);
|
|
342
|
+
return {
|
|
343
|
+
title: "Failed to analyze image",
|
|
344
|
+
description: `Error: ${message}`
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
var index_default = openrouterPlugin;
|
|
351
|
+
export {
|
|
352
|
+
index_default as default,
|
|
353
|
+
openrouterPlugin
|
|
354
|
+
};
|
|
355
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { createOpenRouter } from \"@openrouter/ai-sdk-provider\";\nimport { getProviderBaseURL } from \"@elizaos/core\";\nimport type {\n IAgentRuntime,\n ModelTypeName,\n ObjectGenerationParams,\n Plugin,\n GenerateTextParams,\n ImageDescriptionParams,\n} from \"@elizaos/core\";\nimport { EventType, logger, ModelType, safeReplacer } from \"@elizaos/core\";\nimport {\n generateObject,\n generateText,\n JSONParseError,\n type JSONValue,\n type LanguageModelUsage,\n} from \"ai\";\nimport { fetch } from \"undici\";\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 */\nfunction 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 OpenAI API base URL from runtime settings, environment variables, or defaults, using provider-aware resolution.\n *\n * @returns The resolved base URL for OpenAI API requests.\n */\nfunction getBaseURL(runtime: IAgentRuntime): string {\n const defaultBaseURL = getSetting(\n runtime,\n \"OPENROUTER_BASE_URL\",\n \"https://openrouter.ai/api/v1\"\n ) as string;\n const providerBaseURL = getProviderBaseURL(\n runtime,\n \"openrouter\",\n defaultBaseURL\n );\n return providerBaseURL || defaultBaseURL;\n}\n\n/**\n * Helper function to get the API key for OpenAI\n *\n * @param runtime The runtime context\n * @returns The configured API key\n */\nfunction 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 */\nfunction getSmallModel(runtime: IAgentRuntime): string {\n return (\n getSetting(runtime, \"OPENROUTER_SMALL_MODEL\") ??\n getSetting(runtime, \"SMALL_MODEL\", \"google/gemini-flash\") ??\n \"google/gemini-flash\"\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 */\nfunction getLargeModel(runtime: IAgentRuntime): string {\n return (\n getSetting(runtime, \"OPENROUTER_LARGE_MODEL\") ??\n getSetting(runtime, \"LARGE_MODEL\", \"google/gemini-pro\") ??\n \"google/gemini-pro\"\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 */\nfunction 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\n/**\n * Create an OpenRouter provider instance with proper configuration\n *\n * @param runtime The runtime context\n * @returns Configured OpenRouter provider instance\n */\nfunction 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 createOpenAI.\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\n/**\n * Helper function to generate objects using specified model type\n */\nasync function generateObjectByModelType(\n runtime: IAgentRuntime,\n params: ObjectGenerationParams,\n modelType: string,\n getModelFn: (runtime: IAgentRuntime) => string\n): Promise<JSONValue> {\n const openrouter = createOpenRouterProvider(runtime);\n const modelName = getModelFn(runtime);\n const temperature = params.temperature ?? 0;\n const schemaPresent = !!params.schema;\n\n if (schemaPresent) {\n logger.info(\n `Using ${modelType} without schema validation (schema provided but output=no-schema)`\n );\n }\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(\n runtime,\n modelType as ModelTypeName,\n params.prompt,\n usage\n );\n }\n return object;\n } catch (error: 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.info(\"[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 const exception =\n repairParseError instanceof Error\n ? repairParseError\n : new Error(message);\n throw exception;\n }\n } else {\n const errMsg = error instanceof Error ? error.message : String(error);\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 const exception = error instanceof Error ? error : new Error(message);\n throw exception;\n }\n }\n}\n\n/**\n * Returns a function to repair JSON text\n */\nfunction 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/**\n * Emits a model usage event\n * @param runtime The runtime context\n * @param type The model type\n * @param prompt The prompt used\n * @param usage The LLM usage data\n */\nfunction 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\n/**\n * Defines the OpenAI plugin with its name, description, and configuration options.\n * @type {Plugin}\n */\nexport const openrouterPlugin: Plugin = {\n name: \"openrouter\",\n description: \"OpenAI 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 try {\n if (!getApiKey(runtime)) {\n logger.warn(\n \"OPENROUTER_API_KEY is not set in environment - OpenAI 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 `OpenAI API key validation failed: ${response.statusText}`\n );\n logger.warn(\n \"OpenAI functionality will be limited until a valid API key is provided\"\n );\n } else {\n logger.log(\"OpenAI 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 OpenAI API key: ${message}`);\n logger.warn(\n \"OpenAI 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 `OpenAI plugin configuration issue: ${message} - You need to configure the OPENROUTER_API_KEY in your environment variables`\n );\n }\n },\n models: {\n [ModelType.TEXT_SMALL]: async (\n runtime: IAgentRuntime,\n { prompt, stopSequences = [] }: GenerateTextParams\n ) => {\n const temperature = 0.7;\n const frequency_penalty = 0.7;\n const presence_penalty = 0.7;\n const max_response_length = 8192;\n\n const openrouter = createOpenRouterProvider(runtime);\n const modelName = getSmallModel(runtime);\n\n logger.log(\"generating text\");\n logger.log(prompt);\n\n let responseText = \"\";\n let usage: LanguageModelUsage | undefined;\n const model = openrouter.chat(modelName);\n const system = runtime.character.system ?? undefined;\n const callParams = {\n model: modelName,\n prompt: prompt,\n system: system,\n temperature: temperature,\n maxTokens: max_response_length,\n frequencyPenalty: frequency_penalty,\n presencePenalty: presence_penalty,\n stopSequences: stopSequences,\n };\n logger.debug(\n `[TEXT_SMALL] Calling generateText with params: ${JSON.stringify(callParams, safeReplacer())}`\n );\n try {\n const { text, usage: usageData } = await generateText({\n model: model,\n prompt: prompt,\n system: system,\n temperature: temperature,\n maxTokens: max_response_length,\n frequencyPenalty: frequency_penalty,\n presencePenalty: presence_penalty,\n stopSequences: stopSequences,\n });\n responseText = text;\n usage = usageData;\n } catch (e: unknown) {\n logger.error(\n `[TEXT_SMALL] Error during generateText call: ${JSON.stringify(e, Object.getOwnPropertyNames(e), 2)}`\n );\n }\n\n if (usage) {\n emitModelUsageEvent(runtime, ModelType.TEXT_SMALL, prompt, usage);\n }\n\n return responseText;\n },\n [ModelType.TEXT_LARGE]: async (\n runtime: IAgentRuntime,\n {\n prompt,\n stopSequences = [],\n maxTokens = 8192,\n temperature = 0.7,\n frequencyPenalty = 0.7,\n presencePenalty = 0.7,\n }: GenerateTextParams\n ) => {\n const openrouter = createOpenRouterProvider(runtime);\n const modelName = getLargeModel(runtime);\n\n logger.log(\"generating text\");\n logger.log(prompt);\n\n let responseText = \"\";\n let usage: LanguageModelUsage | undefined;\n try {\n const { text, usage: usageData } = await generateText({\n model: openrouter.chat(modelName),\n prompt: prompt,\n system: runtime.character.system ?? undefined,\n temperature: temperature,\n maxTokens: maxTokens,\n frequencyPenalty: frequencyPenalty,\n presencePenalty: presencePenalty,\n stopSequences: stopSequences,\n });\n responseText = text;\n usage = usageData;\n } catch (e: unknown) {\n logger.error(\n `[TEXT_LARGE] Error during generateText call: ${JSON.stringify(e, Object.getOwnPropertyNames(e), 2)}`\n );\n }\n\n if (usage) {\n emitModelUsageEvent(runtime, ModelType.TEXT_LARGE, prompt, usage);\n }\n\n return responseText;\n },\n [ModelType.OBJECT_SMALL]: async (\n runtime: IAgentRuntime,\n params: ObjectGenerationParams\n ) => {\n return generateObjectByModelType(\n runtime,\n params,\n ModelType.OBJECT_SMALL,\n getSmallModel\n );\n },\n [ModelType.OBJECT_LARGE]: async (\n runtime: IAgentRuntime,\n params: ObjectGenerationParams\n ) => {\n return generateObjectByModelType(\n runtime,\n params,\n ModelType.OBJECT_LARGE,\n getLargeModel\n );\n },\n [ModelType.IMAGE_DESCRIPTION]: async (\n runtime: IAgentRuntime,\n params: ImageDescriptionParams | string\n ) => {\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\",\n content: [\n { type: \"text\", text: promptText },\n { type: \"image_url\", image_url: { url: imageUrl } },\n ],\n },\n ];\n\n try {\n logger.log(\"Sending image description request to OpenRouter\");\n const model = openrouter.chat(modelName);\n\n const { text: responseText } = await generateText({\n model: model,\n prompt: JSON.stringify(messages),\n maxTokens: maxTokens,\n });\n\n logger.log(\"Received response for image description\");\n\n // Try to parse the response 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 } 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 },\n};\nexport default openrouterPlugin;\n"],"mappings":";AAAA,SAAS,wBAAwB;AACjC,SAAS,0BAA0B;AASnC,SAAS,WAAW,QAAQ,WAAW,oBAAoB;AAC3D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAS,aAAa;AAStB,SAAS,WACP,SACA,KACA,cACoB;AACpB,SAAO,QAAQ,WAAW,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK;AACxD;AAOA,SAAS,WAAW,SAAgC;AAClD,QAAM,iBAAiB;AAAA,IACrB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,QAAM,kBAAkB;AAAA,IACtB;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,SAAO,mBAAmB;AAC5B;AAQA,SAAS,UAAU,SAA4C;AAC7D,SAAO,WAAW,SAAS,oBAAoB;AACjD;AAQA,SAAS,cAAc,SAAgC;AACrD,SACE,WAAW,SAAS,wBAAwB,KAC5C,WAAW,SAAS,eAAe,qBAAqB,KACxD;AAEJ;AAQA,SAAS,cAAc,SAAgC;AACrD,SACE,WAAW,SAAS,wBAAwB,KAC5C,WAAW,SAAS,eAAe,mBAAmB,KACtD;AAEJ;AAQA,SAAS,cAAc,SAAgC;AACrD,SACE,WAAW,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E;AAAA,UACpD;AAAA,QACF;AAAA,MACF;AAEA,UAAI;AACF,eAAO,IAAI,iDAAiD;AAC5D,cAAM,QAAQ,WAAW,KAAK,SAAS;AAEvC,cAAM,EAAE,MAAM,aAAa,IAAI,MAAM,aAAa;AAAA,UAChD;AAAA,UACA,QAAQ,KAAK,UAAU,QAAQ;AAAA,UAC/B;AAAA,QACF,CAAC;AAED,eAAO,IAAI,yCAAyC;AAGpD,YAAI;AACF,gBAAM,eAAe,KAAK,MAAM,YAAY;AAC5C,cAAI,aAAa,SAAS,aAAa,aAAa;AAClD,mBAAO;AAAA,UACT;AAAA,QACF,SAAS,GAAG;AAEV,iBAAO,MAAM,+CAA+C,CAAC,EAAE;AAAA,QACjE;AAGA,cAAM,aAAa,aAAa,MAAM,2BAA2B;AACjE,cAAM,QAAQ,aAAa,CAAC,GAAG,KAAK,KAAK;AACzC,cAAM,cAAc,aACjB,QAAQ,6BAA6B,EAAE,EACvC,KAAK;AAER,eAAO,EAAE,OAAO,YAAY;AAAA,MAC9B,SAAS,OAAgB;AACvB,cAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,eAAO,MAAM,0BAA0B,OAAO,EAAE;AAChD,eAAO;AAAA,UACL,OAAO;AAAA,UACP,aAAa,UAAU,OAAO;AAAA,QAChC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AACA,IAAO,gBAAQ;","names":[]}
|
package/package.json
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@elizaos/plugin-openrouter",
|
|
3
|
+
"version": "1.0.0-beta.51",
|
|
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": "https://github.com/elizaos-plugins/plugin-openrouter"
|
|
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.0.0-beta.51",
|
|
28
|
+
"@openrouter/ai-sdk-provider": "^0.4.5",
|
|
29
|
+
"ai": "^4.3.15",
|
|
30
|
+
"undici": "^7.9.0"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"prettier": "3.5.3",
|
|
34
|
+
"tsup": "8.4.0",
|
|
35
|
+
"typescript": "5.8.3",
|
|
36
|
+
"vitest": "3.1.3",
|
|
37
|
+
"dotenv": "^16.5.0"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "tsup",
|
|
41
|
+
"dev": "tsup --watch",
|
|
42
|
+
"lint": "prettier --write ./src",
|
|
43
|
+
"clean": "rm -rf dist .turbo node_modules .turbo-tsconfig.json tsconfig.tsbuildinfo",
|
|
44
|
+
"format": "prettier --write ./src",
|
|
45
|
+
"format:check": "prettier --check ./src",
|
|
46
|
+
"test": "vitest run",
|
|
47
|
+
"test:watch": "vitest"
|
|
48
|
+
},
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public"
|
|
51
|
+
},
|
|
52
|
+
"agentConfig": {
|
|
53
|
+
"pluginType": "elizaos:plugin:1.0.0",
|
|
54
|
+
"pluginParameters": {
|
|
55
|
+
"OPENROUTER_API_KEY": {
|
|
56
|
+
"type": "string",
|
|
57
|
+
"description": "API key for the service"
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|