@elizaos/plugin-openai 1.0.0-beta.45 → 1.0.0-beta.47

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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../../../node_modules/@opentelemetry/api/src/platform/node/globalThis.ts","../../../node_modules/@opentelemetry/api/src/version.ts","../../../node_modules/@opentelemetry/api/src/internal/semver.ts","../../../node_modules/@opentelemetry/api/src/internal/global-utils.ts","../../../node_modules/@opentelemetry/api/src/diag/ComponentLogger.ts","../../../node_modules/@opentelemetry/api/src/diag/types.ts","../../../node_modules/@opentelemetry/api/src/diag/internal/logLevelLogger.ts","../../../node_modules/@opentelemetry/api/src/api/diag.ts","../../../node_modules/@opentelemetry/api/src/context/context.ts","../../../node_modules/@opentelemetry/api/src/context/NoopContextManager.ts","../../../node_modules/@opentelemetry/api/src/api/context.ts","../../../node_modules/@opentelemetry/api/src/trace/status.ts","../../../node_modules/@opentelemetry/api/src/context-api.ts"],"sourcesContent":["import { createOpenAI } from '@ai-sdk/openai';\nimport { getProviderBaseURL } from '@elizaos/core';\nimport type {\n IAgentRuntime,\n ImageDescriptionParams,\n ModelTypeName,\n ObjectGenerationParams,\n Plugin,\n ServiceTypeName,\n TextEmbeddingParams,\n TokenizeTextParams,\n DetokenizeTextParams,\n GenerateTextParams,\n} from '@elizaos/core';\nimport {\n EventType,\n logger,\n ModelType,\n VECTOR_DIMS,\n safeReplacer,\n type InstrumentationService,\n ServiceType,\n} from '@elizaos/core';\nimport {\n generateObject,\n generateText,\n JSONParseError,\n type JSONValue,\n type LanguageModelUsage,\n} from 'ai';\nimport { type TiktokenModel, encodingForModel } from 'js-tiktoken';\nimport { fetch, FormData } from 'undici';\nimport { SpanStatusCode, trace, type Span, context } from '@opentelemetry/api';\n\n/**\n * Helper function to get tracer if instrumentation is enabled\n */\nfunction getTracer(runtime: IAgentRuntime) {\n const availableServices = Array.from(runtime.getAllServices().keys());\n logger.debug(`[getTracer] Available services: ${JSON.stringify(availableServices)}`);\n logger.debug(`[getTracer] Attempting to get service with key: ${ServiceType.INSTRUMENTATION}`);\n\n const instrumentationService = runtime.getService<InstrumentationService>(\n ServiceType.INSTRUMENTATION\n );\n\n if (!instrumentationService) {\n logger.warn(`[getTracer] Service ${ServiceType.INSTRUMENTATION} not found in runtime.`);\n return null;\n }\n\n if (!instrumentationService.isEnabled()) {\n logger.debug('[getTracer] Instrumentation service found but is disabled.');\n return null;\n }\n\n logger.debug('[getTracer] Successfully retrieved enabled instrumentation service.');\n return instrumentationService.getTracer('eliza.llm.openai');\n}\n\n/**\n * Helper function to start an LLM span\n */\nasync function startLlmSpan<T>(\n runtime: IAgentRuntime,\n spanName: string,\n attributes: Record<string, string | number | boolean>,\n fn: (span: Span) => Promise<T>\n): Promise<T> {\n const tracer = getTracer(runtime);\n if (!tracer) {\n const dummySpan = {\n setAttribute: () => {},\n setAttributes: () => {},\n addEvent: () => {},\n recordException: () => {},\n setStatus: () => {},\n end: () => {},\n spanContext: () => ({ traceId: '', spanId: '', traceFlags: 0 }),\n } as unknown as Span;\n return fn(dummySpan);\n }\n\n // Get active context to ensure proper nesting\n const activeContext = context.active();\n\n return tracer.startActiveSpan(spanName, { attributes }, activeContext, async (span: Span) => {\n try {\n const result = await fn(span);\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n return result;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR, message });\n span.end();\n throw error;\n }\n });\n}\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(runtime, 'OPENAI_BASE_URL', 'https://api.openai.com/v1');\n logger.debug(`[OpenAI] Default base URL: ${defaultBaseURL}`);\n return getProviderBaseURL(runtime, 'openai', defaultBaseURL);\n}\n\n/**\n * Retrieves the OpenAI API base URL for embeddings, falling back to the general base URL.\n *\n * @returns The resolved base URL for OpenAI embedding requests.\n */\nfunction getEmbeddingBaseURL(runtime: IAgentRuntime): string {\n const embeddingURL = getSetting(runtime, 'OPENAI_EMBEDDING_URL');\n if (embeddingURL) {\n logger.debug(`[OpenAI] Using specific embedding base URL: ${embeddingURL}`);\n return embeddingURL;\n }\n logger.debug('[OpenAI] Falling back to general base URL for embeddings.');\n return getBaseURL(runtime);\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, 'OPENAI_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, 'OPENAI_SMALL_MODEL') ?? getSetting(runtime, 'SMALL_MODEL', 'gpt-4o-mini')\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 getSetting(runtime, 'OPENAI_LARGE_MODEL') ?? getSetting(runtime, 'LARGE_MODEL', 'gpt-4o');\n}\n\n/**\n * Create an OpenAI client with proper configuration\n *\n * @param runtime The runtime context\n * @returns Configured OpenAI client\n */\nfunction createOpenAIClient(runtime: IAgentRuntime) {\n return createOpenAI({\n apiKey: getApiKey(runtime),\n baseURL: getBaseURL(runtime),\n });\n}\n\n/**\n * Asynchronously tokenizes the given text based on the specified model and prompt.\n *\n * @param {ModelTypeName} model - The type of model to use for tokenization.\n * @param {string} prompt - The text prompt to tokenize.\n * @returns {number[]} - An array of tokens representing the encoded prompt.\n */\nasync function tokenizeText(model: ModelTypeName, prompt: string) {\n const modelName =\n model === ModelType.TEXT_SMALL\n ? (process.env.OPENAI_SMALL_MODEL ?? process.env.SMALL_MODEL ?? 'gpt-4o-mini')\n : (process.env.LARGE_MODEL ?? 'gpt-4o');\n const encoding = encodingForModel(modelName as TiktokenModel);\n const tokens = encoding.encode(prompt);\n return tokens;\n}\n\n/**\n * Detokenize a sequence of tokens back into text using the specified model.\n *\n * @param {ModelTypeName} model - The type of model to use for detokenization.\n * @param {number[]} tokens - The sequence of tokens to detokenize.\n * @returns {string} The detokenized text.\n */\nasync function detokenizeText(model: ModelTypeName, tokens: number[]) {\n const modelName =\n model === ModelType.TEXT_SMALL\n ? (process.env.OPENAI_SMALL_MODEL ?? process.env.SMALL_MODEL ?? 'gpt-4o-mini')\n : (process.env.OPENAI_LARGE_MODEL ?? process.env.LARGE_MODEL ?? 'gpt-4o');\n const encoding = encodingForModel(modelName as TiktokenModel);\n return encoding.decode(tokens);\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 openai = createOpenAIClient(runtime);\n const modelName = getModelFn(runtime);\n logger.log(`[OpenAI] Using ${modelType} model: ${modelName}`);\n const temperature = params.temperature ?? 0;\n const schemaPresent = !!params.schema;\n\n // --- Start Instrumentation ---\n const attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'object_generation',\n 'llm.request.model': modelName,\n 'llm.request.temperature': temperature,\n 'llm.request.schema_present': schemaPresent,\n };\n\n return startLlmSpan(runtime, 'LLM.generateObject', attributes, async (span) => {\n span.addEvent('llm.prompt', { 'prompt.content': params.prompt });\n if (schemaPresent) {\n span.addEvent('llm.request.schema', {\n schema: JSON.stringify(params.schema, safeReplacer()),\n });\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: openai.languageModel(modelName),\n output: 'no-schema',\n prompt: params.prompt,\n temperature: temperature,\n experimental_repairText: getJsonRepairFunction(),\n });\n\n span.addEvent('llm.response.processed', {\n 'response.object': JSON.stringify(object, safeReplacer()),\n });\n\n if (usage) {\n span.setAttributes({\n 'llm.usage.prompt_tokens': usage.promptTokens,\n 'llm.usage.completion_tokens': usage.completionTokens,\n 'llm.usage.total_tokens': usage.totalTokens,\n });\n emitModelUsageEvent(runtime, modelType as ModelTypeName, params.prompt, usage);\n }\n return object;\n } catch (error: unknown) {\n if (error instanceof JSONParseError) {\n logger.error(`[generateObject] Failed to parse JSON: ${error.message}`);\n span.recordException(error);\n span.addEvent('llm.error.json_parse', {\n 'error.message': error.message,\n 'error.text': error.text,\n });\n\n span.addEvent('llm.repair.attempt');\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 span.addEvent('llm.repair.success', {\n repaired_object: JSON.stringify(repairedObject, safeReplacer()),\n });\n logger.info('[generateObject] Successfully repaired JSON.');\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'JSON parsing failed but was repaired',\n });\n return repairedObject;\n } catch (repairParseError: unknown) {\n const message =\n repairParseError instanceof Error\n ? repairParseError.message\n : String(repairParseError);\n logger.error(`[generateObject] Failed to parse repaired JSON: ${message}`);\n const exception =\n repairParseError instanceof Error ? repairParseError : new Error(message);\n span.recordException(exception);\n span.addEvent('llm.repair.parse_error', {\n 'error.message': message,\n });\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `JSON repair failed: ${message}`,\n });\n throw repairParseError;\n }\n } else {\n const errMsg = error instanceof Error ? error.message : String(error);\n logger.error('[generateObject] JSON repair failed.');\n span.addEvent('llm.repair.failed');\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `JSON repair failed: ${errMsg}`,\n });\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 span.recordException(exception);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: message,\n });\n throw error;\n }\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 = 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: 'openai',\n type,\n prompt,\n tokens: {\n prompt: usage.promptTokens,\n completion: usage.completionTokens,\n total: usage.totalTokens,\n },\n });\n}\n\n/**\n * function for text-to-speech\n */\nasync function fetchTextToSpeech(runtime: IAgentRuntime, text: string) {\n const apiKey = getApiKey(runtime);\n const model = getSetting(runtime, 'OPENAI_TTS_MODEL', 'gpt-4o-mini-tts');\n const voice = getSetting(runtime, 'OPENAI_TTS_VOICE', 'nova');\n const instructions = getSetting(runtime, 'OPENAI_TTS_INSTRUCTIONS', '');\n const baseURL = getBaseURL(runtime);\n\n try {\n const res = await fetch(`${baseURL}/audio/speech`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n model,\n voice,\n input: text,\n ...(instructions && { instructions }),\n }),\n });\n\n if (!res.ok) {\n const err = await res.text();\n throw new Error(`OpenAI TTS error ${res.status}: ${err}`);\n }\n\n return res.body;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err);\n throw new Error(`Failed to fetch speech from OpenAI TTS: ${message}`);\n }\n}\n\n/**\n * Defines the OpenAI plugin with its name, description, and configuration options.\n * @type {Plugin}\n */\nexport const openaiPlugin: Plugin = {\n name: 'openai',\n description: 'OpenAI plugin',\n config: {\n OPENAI_API_KEY: process.env.OPENAI_API_KEY,\n OPENAI_BASE_URL: process.env.OPENAI_BASE_URL,\n OPENAI_SMALL_MODEL: process.env.OPENAI_SMALL_MODEL,\n OPENAI_LARGE_MODEL: process.env.OPENAI_LARGE_MODEL,\n SMALL_MODEL: process.env.SMALL_MODEL,\n LARGE_MODEL: process.env.LARGE_MODEL,\n OPENAI_EMBEDDING_MODEL: process.env.OPENAI_EMBEDDING_MODEL,\n OPENAI_EMBEDDING_URL: process.env.OPENAI_EMBEDDING_URL,\n OPENAI_EMBEDDING_DIMENSIONS: process.env.OPENAI_EMBEDDING_DIMENSIONS,\n },\n async init(_config, runtime) {\n try {\n if (!getApiKey(runtime)) {\n logger.warn(\n 'OPENAI_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(`OpenAI API key validation failed: ${response.statusText}`);\n logger.warn('OpenAI functionality will be limited until a valid API key is provided');\n } else {\n logger.log('OpenAI API key validated successfully');\n }\n } catch (fetchError: unknown) {\n const message = fetchError instanceof Error ? fetchError.message : String(fetchError);\n logger.warn(`Error validating OpenAI API key: ${message}`);\n logger.warn('OpenAI functionality will be limited until a valid API key is provided');\n }\n } catch (error: unknown) {\n const message =\n (error as { errors?: Array<{ message: string }> })?.errors\n ?.map((e) => e.message)\n .join(', ') || (error instanceof Error ? error.message : String(error));\n logger.warn(\n `OpenAI plugin configuration issue: ${message} - You need to configure the OPENAI_API_KEY in your environment variables`\n );\n }\n },\n models: {\n [ModelType.TEXT_EMBEDDING]: async (\n runtime: IAgentRuntime,\n params: TextEmbeddingParams | string | null\n ): Promise<number[]> => {\n const embeddingModelName = getSetting(\n runtime,\n 'OPENAI_EMBEDDING_MODEL',\n 'text-embedding-3-small'\n );\n const embeddingDimension = Number.parseInt(\n getSetting(runtime, 'OPENAI_EMBEDDING_DIMENSIONS', '1536') || '1536',\n 10\n ) as (typeof VECTOR_DIMS)[keyof typeof VECTOR_DIMS];\n\n // Added log for specific embedding model\n logger.debug(\n `[OpenAI] Using embedding model: ${embeddingModelName} with dimension: ${embeddingDimension}`\n );\n\n if (!Object.values(VECTOR_DIMS).includes(embeddingDimension)) {\n const errorMsg = `Invalid embedding dimension: ${embeddingDimension}. Must be one of: ${Object.values(VECTOR_DIMS).join(', ')}`;\n logger.error(errorMsg);\n throw new Error(errorMsg);\n }\n if (params === null) {\n logger.debug('Creating test embedding for initialization');\n const testVector = Array(embeddingDimension).fill(0);\n testVector[0] = 0.1;\n return testVector;\n }\n let text: string;\n if (typeof params === 'string') {\n text = params;\n } else if (typeof params === 'object' && params.text) {\n text = params.text;\n } else {\n logger.warn('Invalid input format for embedding');\n const fallbackVector = Array(embeddingDimension).fill(0);\n fallbackVector[0] = 0.2;\n return fallbackVector;\n }\n if (!text.trim()) {\n logger.warn('Empty text for embedding');\n const emptyVector = Array(embeddingDimension).fill(0);\n emptyVector[0] = 0.3;\n return emptyVector;\n }\n\n const attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'embedding',\n 'llm.request.model': embeddingModelName,\n 'llm.request.embedding.dimensions': embeddingDimension,\n 'input.text.length': text.length,\n };\n\n return startLlmSpan(runtime, 'LLM.embedding', attributes, async (span) => {\n span.addEvent('llm.prompt', { 'prompt.content': text });\n\n const embeddingBaseURL = getEmbeddingBaseURL(runtime);\n const apiKey = getApiKey(runtime);\n\n if (!apiKey) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'OpenAI API key not configured',\n });\n throw new Error('OpenAI API key not configured');\n }\n\n try {\n const response = await fetch(`${embeddingBaseURL}/embeddings`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n model: embeddingModelName,\n input: text,\n }),\n });\n\n const responseClone = response.clone();\n const rawResponseBody = await responseClone.text();\n span.addEvent('llm.response.raw', {\n 'response.body': rawResponseBody,\n });\n\n if (!response.ok) {\n logger.error(`OpenAI API error: ${response.status} - ${response.statusText}`);\n span.setAttributes({ 'error.api.status': response.status });\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `OpenAI API error: ${response.status} - ${response.statusText}. Response: ${rawResponseBody}`,\n });\n const errorVector = Array(embeddingDimension).fill(0);\n errorVector[0] = 0.4;\n return errorVector;\n }\n\n const data = (await response.json()) as {\n data: [{ embedding: number[] }];\n usage?: { prompt_tokens: number; total_tokens: number };\n };\n\n if (!data?.data?.[0]?.embedding) {\n logger.error('API returned invalid structure');\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'API returned invalid structure',\n });\n const errorVector = Array(embeddingDimension).fill(0);\n errorVector[0] = 0.5;\n return errorVector;\n }\n\n const embedding = data.data[0].embedding;\n span.setAttribute('llm.response.embedding.vector_length', embedding.length);\n\n if (data.usage) {\n span.setAttributes({\n 'llm.usage.prompt_tokens': data.usage.prompt_tokens,\n 'llm.usage.total_tokens': data.usage.total_tokens,\n });\n \n const usage = {\n promptTokens: data.usage.prompt_tokens,\n completionTokens: 0,\n totalTokens: data.usage.total_tokens\n };\n \n emitModelUsageEvent(runtime, ModelType.TEXT_EMBEDDING, text, usage);\n }\n\n logger.log(`Got valid embedding with length ${embedding.length}`);\n return embedding;\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error generating embedding: ${message}`);\n const exception = error instanceof Error ? error : new Error(message);\n span.recordException(exception);\n span.setStatus({ code: SpanStatusCode.ERROR, message: message });\n const errorVector = Array(embeddingDimension).fill(0);\n errorVector[0] = 0.6;\n return errorVector;\n }\n });\n },\n [ModelType.TEXT_TOKENIZER_ENCODE]: async (\n _runtime,\n { prompt, modelType = ModelType.TEXT_LARGE }: TokenizeTextParams\n ) => {\n return await tokenizeText(modelType ?? ModelType.TEXT_LARGE, prompt);\n },\n [ModelType.TEXT_TOKENIZER_DECODE]: async (\n _runtime,\n { tokens, modelType = ModelType.TEXT_LARGE }: DetokenizeTextParams\n ) => {\n return await detokenizeText(modelType ?? ModelType.TEXT_LARGE, tokens);\n },\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 openai = createOpenAIClient(runtime);\n const modelName = getSmallModel(runtime);\n\n logger.log(`[OpenAI] Using TEXT_SMALL model: ${modelName}`);\n logger.log(prompt);\n\n const attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'completion',\n 'llm.request.model': modelName,\n 'llm.request.temperature': temperature,\n 'llm.request.max_tokens': max_response_length,\n 'llm.request.frequency_penalty': frequency_penalty,\n 'llm.request.presence_penalty': presence_penalty,\n 'llm.request.stop_sequences': JSON.stringify(stopSequences),\n };\n\n return startLlmSpan(runtime, 'LLM.generateText', attributes, async (span) => {\n span.addEvent('llm.prompt', { 'prompt.content': prompt });\n\n const { text: openaiResponse, usage } = await generateText({\n model: openai.languageModel(modelName),\n prompt: prompt,\n system: runtime.character.system ?? undefined,\n temperature: temperature,\n maxTokens: max_response_length,\n frequencyPenalty: frequency_penalty,\n presencePenalty: presence_penalty,\n stopSequences: stopSequences,\n });\n\n span.setAttribute('llm.response.processed.length', openaiResponse.length);\n span.addEvent('llm.response.processed', {\n 'response.content':\n openaiResponse.substring(0, 200) + (openaiResponse.length > 200 ? '...' : ''),\n });\n\n if (usage) {\n span.setAttributes({\n 'llm.usage.prompt_tokens': usage.promptTokens,\n 'llm.usage.completion_tokens': usage.completionTokens,\n 'llm.usage.total_tokens': usage.totalTokens,\n });\n emitModelUsageEvent(runtime, ModelType.TEXT_SMALL, prompt, usage);\n }\n\n return openaiResponse;\n });\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 openai = createOpenAIClient(runtime);\n const modelName = getLargeModel(runtime);\n\n logger.log(`[OpenAI] Using TEXT_LARGE model: ${modelName}`);\n logger.log(prompt);\n\n const attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'completion',\n 'llm.request.model': modelName,\n 'llm.request.temperature': temperature,\n 'llm.request.max_tokens': maxTokens,\n 'llm.request.frequency_penalty': frequencyPenalty,\n 'llm.request.presence_penalty': presencePenalty,\n 'llm.request.stop_sequences': JSON.stringify(stopSequences),\n };\n\n return startLlmSpan(runtime, 'LLM.generateText', attributes, async (span) => {\n span.addEvent('llm.prompt', { 'prompt.content': prompt });\n\n const { text: openaiResponse, usage } = await generateText({\n model: openai.languageModel(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\n span.setAttribute('llm.response.processed.length', openaiResponse.length);\n span.addEvent('llm.response.processed', {\n 'response.content':\n openaiResponse.substring(0, 200) + (openaiResponse.length > 200 ? '...' : ''),\n });\n\n if (usage) {\n span.setAttributes({\n 'llm.usage.prompt_tokens': usage.promptTokens,\n 'llm.usage.completion_tokens': usage.completionTokens,\n 'llm.usage.total_tokens': usage.totalTokens,\n });\n emitModelUsageEvent(runtime, ModelType.TEXT_LARGE, prompt, usage);\n }\n\n return openaiResponse;\n });\n },\n [ModelType.IMAGE]: async (\n runtime: IAgentRuntime,\n params: {\n prompt: string;\n n?: number;\n size?: string;\n }\n ) => {\n const n = params.n || 1;\n const size = params.size || '1024x1024';\n const prompt = params.prompt;\n const modelName = 'dall-e-3'; // Default DALL-E model\n logger.log(`[OpenAI] Using IMAGE model: ${modelName}`);\n\n const attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'image_generation',\n 'llm.request.image.size': size,\n 'llm.request.image.count': n,\n };\n\n return startLlmSpan(runtime, 'LLM.imageGeneration', attributes, async (span) => {\n span.addEvent('llm.prompt', { 'prompt.content': prompt });\n\n const baseURL = getBaseURL(runtime);\n const apiKey = getApiKey(runtime);\n\n if (!apiKey) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'OpenAI API key not configured',\n });\n throw new Error('OpenAI API key not configured');\n }\n\n try {\n const response = await fetch(`${baseURL}/images/generations`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n prompt: prompt,\n n: n,\n size: size,\n }),\n });\n\n const responseClone = response.clone();\n const rawResponseBody = await responseClone.text();\n span.addEvent('llm.response.raw', {\n 'response.body': rawResponseBody,\n });\n\n if (!response.ok) {\n span.setAttributes({ 'error.api.status': response.status });\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `Failed to generate image: ${response.statusText}. Response: ${rawResponseBody}`,\n });\n throw new Error(`Failed to generate image: ${response.statusText}`);\n }\n\n const data = await response.json();\n const typedData = data as { data: { url: string }[] };\n\n span.addEvent('llm.response.processed', {\n 'response.urls': JSON.stringify(typedData.data),\n });\n\n return typedData.data;\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n const exception = error instanceof Error ? error : new Error(message);\n span.recordException(exception);\n span.setStatus({ code: SpanStatusCode.ERROR, message: message });\n throw error;\n }\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 = 'gpt-4o-mini';\n logger.log(`[OpenAI] Using IMAGE_DESCRIPTION model: ${modelName}`);\n const maxTokens = 300;\n\n if (typeof params === 'string') {\n imageUrl = params;\n promptText = '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 attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'chat',\n 'llm.request.model': modelName,\n 'llm.request.max_tokens': maxTokens,\n 'llm.request.image.url': imageUrl,\n };\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 return startLlmSpan(runtime, 'LLM.imageDescription', attributes, async (span) => {\n span.addEvent('llm.prompt', {\n 'prompt.content': JSON.stringify(messages, safeReplacer()),\n });\n\n const baseURL = getBaseURL(runtime);\n const apiKey = getApiKey(runtime);\n\n if (!apiKey) {\n logger.error('OpenAI API key not set');\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'OpenAI API key not configured',\n });\n return {\n title: 'Failed to analyze image',\n description: 'API key not configured',\n };\n }\n\n try {\n const response = await fetch(`${baseURL}/chat/completions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: modelName,\n messages: messages,\n max_tokens: maxTokens,\n }),\n });\n\n const responseClone = response.clone();\n const rawResponseBody = await responseClone.text();\n span.addEvent('llm.response.raw', {\n 'response.body': rawResponseBody,\n });\n\n if (!response.ok) {\n span.setAttributes({ 'error.api.status': response.status });\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `OpenAI API error: ${response.status}. Response: ${rawResponseBody}`,\n });\n throw new Error(`OpenAI API error: ${response.status}`);\n }\n\n const result: unknown = await response.json();\n\n type OpenAIResponseType = {\n choices?: Array<{\n message?: { content?: string };\n finish_reason?: string;\n }>;\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n };\n };\n\n const typedResult = result as OpenAIResponseType;\n const content = typedResult.choices?.[0]?.message?.content;\n\n if (typedResult.usage) {\n span.setAttributes({\n 'llm.usage.prompt_tokens': typedResult.usage.prompt_tokens,\n 'llm.usage.completion_tokens': typedResult.usage.completion_tokens,\n 'llm.usage.total_tokens': typedResult.usage.total_tokens,\n });\n \n emitModelUsageEvent(runtime, ModelType.IMAGE_DESCRIPTION, \n typeof params === 'string' ? params : params.prompt || '',\n {\n promptTokens: typedResult.usage.prompt_tokens,\n completionTokens: typedResult.usage.completion_tokens,\n totalTokens: typedResult.usage.total_tokens\n }\n );\n }\n if (typedResult.choices?.[0]?.finish_reason) {\n span.setAttribute('llm.response.finish_reason', typedResult.choices[0].finish_reason);\n }\n\n if (!content) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'No content in API response',\n });\n return {\n title: 'Failed to analyze image',\n description: 'No response from API',\n };\n }\n\n const titleMatch = content.match(/title[:\\s]+(.+?)(?:\\n|$)/i);\n const title = titleMatch?.[1]?.trim() || 'Image Analysis';\n const description = content.replace(/title[:\\s]+(.+?)(?:\\n|$)/i, '').trim();\n\n const processedResult = { title, description };\n span.addEvent('llm.response.processed', {\n 'response.object': JSON.stringify(processedResult, safeReplacer()),\n });\n\n return processedResult;\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error analyzing image: ${message}`);\n const exception = error instanceof Error ? error : new Error(message);\n span.recordException(exception);\n span.setStatus({ code: SpanStatusCode.ERROR, message: message });\n return {\n title: 'Failed to analyze image',\n description: `Error: ${message}`,\n };\n }\n });\n },\n [ModelType.TRANSCRIPTION]: async (runtime: IAgentRuntime, audioBuffer: Buffer) => {\n logger.log('audioBuffer', audioBuffer);\n\n const modelName = 'whisper-1';\n logger.log(`[OpenAI] Using TRANSCRIPTION model: ${modelName}`);\n const attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'transcription',\n 'llm.request.model': modelName,\n 'llm.request.audio.input_size_bytes': audioBuffer?.length || 0,\n };\n\n return startLlmSpan(runtime, 'LLM.transcription', attributes, async (span) => {\n span.addEvent('llm.prompt', {\n 'prompt.info': 'Audio buffer for transcription',\n });\n\n const baseURL = getBaseURL(runtime);\n const apiKey = getApiKey(runtime);\n\n if (!apiKey) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'OpenAI API key not configured',\n });\n throw new Error('OpenAI API key not configured - Cannot make request');\n }\n if (!audioBuffer || audioBuffer.length === 0) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'Audio buffer is empty or invalid',\n });\n throw new Error('Audio buffer is empty or invalid for transcription');\n }\n\n const formData = new FormData();\n formData.append('file', new Blob([audioBuffer]), 'recording.mp3');\n formData.append('model', 'whisper-1');\n\n try {\n const response = await fetch(`${baseURL}/audio/transcriptions`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n body: formData,\n });\n\n const responseClone = response.clone();\n const rawResponseBody = await responseClone.text();\n span.addEvent('llm.response.raw', {\n 'response.body': rawResponseBody,\n });\n\n logger.log('response', response);\n\n if (!response.ok) {\n span.setAttributes({ 'error.api.status': response.status });\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `Failed to transcribe audio: ${response.statusText}. Response: ${rawResponseBody}`,\n });\n throw new Error(`Failed to transcribe audio: ${response.statusText}`);\n }\n\n const data = (await response.json()) as { text: string };\n const processedText = data.text;\n\n span.setAttribute('llm.response.processed.length', processedText.length);\n span.addEvent('llm.response.processed', {\n 'response.text': processedText,\n });\n\n return processedText;\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n const exception = error instanceof Error ? error : new Error(message);\n span.recordException(exception);\n span.setStatus({ code: SpanStatusCode.ERROR, message: message });\n throw error;\n }\n });\n },\n [ModelType.TEXT_TO_SPEECH]: async (runtime: IAgentRuntime, text: string) => {\n const ttsModelName = getSetting(runtime, 'OPENAI_TTS_MODEL', 'gpt-4o-mini-tts');\n const attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'tts',\n 'llm.request.model': ttsModelName,\n 'input.text.length': text.length,\n };\n return startLlmSpan(runtime, 'LLM.tts', attributes, async (span) => {\n logger.log(`[OpenAI] Using TEXT_TO_SPEECH model: ${ttsModelName}`);\n span.addEvent('llm.prompt', { 'prompt.content': text });\n try {\n const speechStream = await fetchTextToSpeech(runtime, text);\n span.addEvent('llm.response.success', {\n info: 'Speech stream generated',\n });\n return speechStream;\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n const exception = error instanceof Error ? error : new Error(message);\n span.recordException(exception);\n span.setStatus({ code: SpanStatusCode.ERROR, message: message });\n throw error;\n }\n });\n },\n [ModelType.OBJECT_SMALL]: async (runtime: IAgentRuntime, params: ObjectGenerationParams) => {\n return generateObjectByModelType(runtime, params, ModelType.OBJECT_SMALL, getSmallModel);\n },\n [ModelType.OBJECT_LARGE]: async (runtime: IAgentRuntime, params: ObjectGenerationParams) => {\n return generateObjectByModelType(runtime, params, ModelType.OBJECT_LARGE, getLargeModel);\n },\n },\n tests: [\n {\n name: 'openai_plugin_tests',\n tests: [\n {\n name: 'openai_test_url_and_api_key_validation',\n fn: async (runtime: IAgentRuntime) => {\n const baseURL = getBaseURL(runtime);\n const response = await fetch(`${baseURL}/models`, {\n headers: {\n Authorization: `Bearer ${getApiKey(runtime)}`,\n },\n });\n const data = await response.json();\n logger.log('Models Available:', (data as { data?: unknown[] })?.data?.length ?? 'N/A');\n if (!response.ok) {\n throw new Error(`Failed to validate OpenAI API key: ${response.statusText}`);\n }\n },\n },\n {\n name: 'openai_test_text_embedding',\n fn: async (runtime: IAgentRuntime) => {\n try {\n const embedding = await runtime.useModel(ModelType.TEXT_EMBEDDING, {\n text: 'Hello, world!',\n });\n logger.log('embedding', embedding);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error in test_text_embedding: ${message}`);\n throw error;\n }\n },\n },\n {\n name: 'openai_test_text_large',\n fn: async (runtime: IAgentRuntime) => {\n try {\n const text = await runtime.useModel(ModelType.TEXT_LARGE, {\n prompt: 'What is the nature of reality in 10 words?',\n });\n if (text.length === 0) {\n throw new Error('Failed to generate text');\n }\n logger.log('generated with test_text_large:', text);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error in test_text_large: ${message}`);\n throw error;\n }\n },\n },\n {\n name: 'openai_test_text_small',\n fn: async (runtime: IAgentRuntime) => {\n try {\n const text = await runtime.useModel(ModelType.TEXT_SMALL, {\n prompt: 'What is the nature of reality in 10 words?',\n });\n if (text.length === 0) {\n throw new Error('Failed to generate text');\n }\n logger.log('generated with test_text_small:', text);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error in test_text_small: ${message}`);\n throw error;\n }\n },\n },\n {\n name: 'openai_test_image_generation',\n fn: async (runtime: IAgentRuntime) => {\n logger.log('openai_test_image_generation');\n try {\n const image = await runtime.useModel(ModelType.IMAGE, {\n prompt: 'A beautiful sunset over a calm ocean',\n n: 1,\n size: '1024x1024',\n });\n logger.log('generated with test_image_generation:', image);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error in test_image_generation: ${message}`);\n throw error;\n }\n },\n },\n {\n name: 'image-description',\n fn: async (runtime: IAgentRuntime) => {\n try {\n logger.log('openai_test_image_description');\n try {\n const result = await runtime.useModel(\n ModelType.IMAGE_DESCRIPTION,\n 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/1c/Vitalik_Buterin_TechCrunch_London_2015_%28cropped%29.jpg/537px-Vitalik_Buterin_TechCrunch_London_2015_%28cropped%29.jpg'\n );\n\n if (\n result &&\n typeof result === 'object' &&\n 'title' in result &&\n 'description' in result\n ) {\n logger.log('Image description:', result);\n } else {\n logger.error('Invalid image description result format:', result);\n }\n } catch (e: unknown) {\n const message = e instanceof Error ? e.message : String(e);\n logger.error(`Error in image description test: ${message}`);\n }\n } catch (e: unknown) {\n const message = e instanceof Error ? e.message : String(e);\n logger.error(`Error in openai_test_image_description: ${message}`);\n }\n },\n },\n {\n name: 'openai_test_transcription',\n fn: async (runtime: IAgentRuntime) => {\n logger.log('openai_test_transcription');\n try {\n const response = await fetch(\n 'https://upload.wikimedia.org/wikipedia/en/4/40/Chris_Benoit_Voice_Message.ogg'\n );\n const arrayBuffer = await response.arrayBuffer();\n const transcription = await runtime.useModel(\n ModelType.TRANSCRIPTION,\n Buffer.from(new Uint8Array(arrayBuffer))\n );\n logger.log('generated with test_transcription:', transcription);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error in test_transcription: ${message}`);\n throw error;\n }\n },\n },\n {\n name: 'openai_test_text_tokenizer_encode',\n fn: async (runtime: IAgentRuntime) => {\n const prompt = 'Hello tokenizer encode!';\n const tokens = await runtime.useModel(ModelType.TEXT_TOKENIZER_ENCODE, { prompt });\n if (!Array.isArray(tokens) || tokens.length === 0) {\n throw new Error('Failed to tokenize text: expected non-empty array of tokens');\n }\n logger.log('Tokenized output:', tokens);\n },\n },\n {\n name: 'openai_test_text_tokenizer_decode',\n fn: async (runtime: IAgentRuntime) => {\n const prompt = 'Hello tokenizer decode!';\n const tokens = await runtime.useModel(ModelType.TEXT_TOKENIZER_ENCODE, { prompt });\n const decodedText = await runtime.useModel(ModelType.TEXT_TOKENIZER_DECODE, { tokens });\n if (decodedText !== prompt) {\n throw new Error(\n `Decoded text does not match original. Expected \"${prompt}\", got \"${decodedText}\"`\n );\n }\n logger.log('Decoded text:', decodedText);\n },\n },\n {\n name: 'openai_test_text_to_speech',\n fn: async (runtime: IAgentRuntime) => {\n try {\n const text = 'Hello, this is a test for text-to-speech.';\n const response = await fetchTextToSpeech(runtime, text);\n if (!response) {\n throw new Error('Failed to generate speech');\n }\n logger.log('Generated speech successfully');\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error in openai_test_text_to_speech: ${message}`);\n throw error;\n }\n },\n },\n ],\n },\n ],\n};\nexport default openaiPlugin;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.9.0';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VERSION } from '../version';\n\nconst re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(\n ownVersion: string\n): (globalVersion: string) => boolean {\n const acceptedVersions = new Set<string>([ownVersion]);\n const rejectedVersions = new Set<string>();\n\n const myVersionMatch = ownVersion.match(re);\n if (!myVersionMatch) {\n // we cannot guarantee compatibility so we always return noop\n return () => false;\n }\n\n const ownVersionParsed = {\n major: +myVersionMatch[1],\n minor: +myVersionMatch[2],\n patch: +myVersionMatch[3],\n prerelease: myVersionMatch[4],\n };\n\n // if ownVersion has a prerelease tag, versions must match exactly\n if (ownVersionParsed.prerelease != null) {\n return function isExactmatch(globalVersion: string): boolean {\n return globalVersion === ownVersion;\n };\n }\n\n function _reject(v: string) {\n rejectedVersions.add(v);\n return false;\n }\n\n function _accept(v: string) {\n acceptedVersions.add(v);\n return true;\n }\n\n return function isCompatible(globalVersion: string): boolean {\n if (acceptedVersions.has(globalVersion)) {\n return true;\n }\n\n if (rejectedVersions.has(globalVersion)) {\n return false;\n }\n\n const globalVersionMatch = globalVersion.match(re);\n if (!globalVersionMatch) {\n // cannot parse other version\n // we cannot guarantee compatibility so we always noop\n return _reject(globalVersion);\n }\n\n const globalVersionParsed = {\n major: +globalVersionMatch[1],\n minor: +globalVersionMatch[2],\n patch: +globalVersionMatch[3],\n prerelease: globalVersionMatch[4],\n };\n\n // if globalVersion has a prerelease tag, versions must match exactly\n if (globalVersionParsed.prerelease != null) {\n return _reject(globalVersion);\n }\n\n // major versions must match\n if (ownVersionParsed.major !== globalVersionParsed.major) {\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.major === 0) {\n if (\n ownVersionParsed.minor === globalVersionParsed.minor &&\n ownVersionParsed.patch <= globalVersionParsed.patch\n ) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n };\n}\n\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport const isCompatible = _makeCompatibilityCheck(VERSION);\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { ContextManager } from '../context/types';\nimport { DiagLogger } from '../diag/types';\nimport { _globalThis } from '../platform';\nimport { TextMapPropagator } from '../propagation/TextMapPropagator';\nimport type { TracerProvider } from '../trace/tracer_provider';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\n\nconst major = VERSION.split('.')[0];\nconst GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\n `opentelemetry.js.api.${major}`\n);\n\nconst _global = _globalThis as OTelGlobal;\n\nexport function registerGlobal<Type extends keyof OTelGlobalAPI>(\n type: Type,\n instance: OTelGlobalAPI[Type],\n diag: DiagLogger,\n allowOverride = false\n): boolean {\n const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = _global[\n GLOBAL_OPENTELEMETRY_API_KEY\n ] ?? {\n version: VERSION,\n });\n\n if (!allowOverride && api[type]) {\n // already registered an API of this type\n const err = new Error(\n `@opentelemetry/api: Attempted duplicate registration of API: ${type}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n if (api.version !== VERSION) {\n // All registered APIs must be of the same version exactly\n const err = new Error(\n `@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n api[type] = instance;\n diag.debug(\n `@opentelemetry/api: Registered a global for ${type} v${VERSION}.`\n );\n\n return true;\n}\n\nexport function getGlobal<Type extends keyof OTelGlobalAPI>(\n type: Type\n): OTelGlobalAPI[Type] | undefined {\n const globalVersion = _global[GLOBAL_OPENTELEMETRY_API_KEY]?.version;\n if (!globalVersion || !isCompatible(globalVersion)) {\n return;\n }\n return _global[GLOBAL_OPENTELEMETRY_API_KEY]?.[type];\n}\n\nexport function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger) {\n diag.debug(\n `@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`\n );\n const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\n if (api) {\n delete api[type];\n }\n}\n\ntype OTelGlobal = {\n [GLOBAL_OPENTELEMETRY_API_KEY]?: OTelGlobalAPI;\n};\n\ntype OTelGlobalAPI = {\n version: string;\n\n diag?: DiagLogger;\n trace?: TracerProvider;\n context?: ContextManager;\n metrics?: MeterProvider;\n propagation?: TextMapPropagator;\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal } from '../internal/global-utils';\nimport { ComponentLoggerOptions, DiagLogger, DiagLogFunction } from './types';\n\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nexport class DiagComponentLogger implements DiagLogger {\n private _namespace: string;\n\n constructor(props: ComponentLoggerOptions) {\n this._namespace = props.namespace || 'DiagComponentLogger';\n }\n\n public debug(...args: any[]): void {\n return logProxy('debug', this._namespace, args);\n }\n\n public error(...args: any[]): void {\n return logProxy('error', this._namespace, args);\n }\n\n public info(...args: any[]): void {\n return logProxy('info', this._namespace, args);\n }\n\n public warn(...args: any[]): void {\n return logProxy('warn', this._namespace, args);\n }\n\n public verbose(...args: any[]): void {\n return logProxy('verbose', this._namespace, args);\n }\n}\n\nfunction logProxy(\n funcName: keyof DiagLogger,\n namespace: string,\n args: any\n): void {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) {\n return;\n }\n\n args.unshift(namespace);\n return logger[funcName](...(args as Parameters<DiagLogFunction>));\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type DiagLogFunction = (message: string, ...args: unknown[]) => void;\n\n/**\n * Defines an internal diagnostic logger interface which is used to log internal diagnostic\n * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function.\n * API provided implementations include :-\n * - a No-Op {@link createNoopDiagLogger}\n * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger}\n * - a general Console {@link DiagConsoleLogger} version.\n */\nexport interface DiagLogger {\n /** Log an error scenario that was not expected and caused the requested operation to fail. */\n error: DiagLogFunction;\n\n /**\n * Log a warning scenario to inform the developer of an issues that should be investigated.\n * The requested operation may or may not have succeeded or completed.\n */\n warn: DiagLogFunction;\n\n /**\n * Log a general informational message, this should not affect functionality.\n * This is also the default logging level so this should NOT be used for logging\n * debugging level information.\n */\n info: DiagLogFunction;\n\n /**\n * Log a general debug message that can be useful for identifying a failure.\n * Information logged at this level may include diagnostic details that would\n * help identify a failure scenario.\n * For example: Logging the order of execution of async operations.\n */\n debug: DiagLogFunction;\n\n /**\n * Log a detailed (verbose) trace level logging that can be used to identify failures\n * where debug level logging would be insufficient, this level of tracing can include\n * input and output parameters and as such may include PII information passing through\n * the API. As such it is recommended that this level of tracing should not be enabled\n * in a production environment.\n */\n verbose: DiagLogFunction;\n}\n\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport enum DiagLogLevel {\n /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n NONE = 0,\n\n /** Identifies an error scenario */\n ERROR = 30,\n\n /** Identifies a warning scenario */\n WARN = 50,\n\n /** General informational log message */\n INFO = 60,\n\n /** General debug log message */\n DEBUG = 70,\n\n /**\n * Detailed trace level logging should only be used for development, should only be set\n * in a development environment.\n */\n VERBOSE = 80,\n\n /** Used to set the logging level to include all logging */\n ALL = 9999,\n}\n\n/**\n * Defines options for ComponentLogger\n */\nexport interface ComponentLoggerOptions {\n namespace: string;\n}\n\nexport interface DiagLoggerOptions {\n /**\n * The {@link DiagLogLevel} used to filter logs sent to the logger.\n *\n * @defaultValue DiagLogLevel.INFO\n */\n logLevel?: DiagLogLevel;\n\n /**\n * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered.\n */\n suppressOverrideMessage?: boolean;\n}\n\nexport interface DiagLoggerApi {\n /**\n * Set the global DiagLogger and DiagLogLevel.\n * If a global diag logger is already set, this will override it.\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean;\n\n /**\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogFunction, DiagLogger, DiagLogLevel } from '../types';\n\nexport function createLogLevelDiagLogger(\n maxLevel: DiagLogLevel,\n logger: DiagLogger\n): DiagLogger {\n if (maxLevel < DiagLogLevel.NONE) {\n maxLevel = DiagLogLevel.NONE;\n } else if (maxLevel > DiagLogLevel.ALL) {\n maxLevel = DiagLogLevel.ALL;\n }\n\n // In case the logger is null or undefined\n logger = logger || {};\n\n function _filterFunc(\n funcName: keyof DiagLogger,\n theLevel: DiagLogLevel\n ): DiagLogFunction {\n const theFunc = logger[funcName];\n\n if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n return theFunc.bind(logger);\n }\n return function () {};\n }\n\n return {\n error: _filterFunc('error', DiagLogLevel.ERROR),\n warn: _filterFunc('warn', DiagLogLevel.WARN),\n info: _filterFunc('info', DiagLogLevel.INFO),\n debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport {\n ComponentLoggerOptions,\n DiagLogFunction,\n DiagLogger,\n DiagLoggerApi,\n DiagLogLevel,\n} from '../diag/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\n\nconst API_NAME = 'diag';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n */\nexport class DiagAPI implements DiagLogger, DiagLoggerApi {\n private static _instance?: DiagAPI;\n\n /** Get the singleton instance of the DiagAPI API */\n public static instance(): DiagAPI {\n if (!this._instance) {\n this._instance = new DiagAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Private internal constructor\n * @private\n */\n private constructor() {\n function _logProxy(funcName: keyof DiagLogger): DiagLogFunction {\n return function (...args) {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) return;\n return logger[funcName](...args);\n };\n }\n\n // Using self local variable for minification purposes as 'this' cannot be minified\n const self = this;\n\n // DiagAPI specific functions\n\n const setLogger: DiagLoggerApi['setLogger'] = (\n logger,\n optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }\n ) => {\n if (logger === self) {\n // There isn't much we can do here.\n // Logging to the console might break the user application.\n // Try to log to self. If a logger was previously registered it will receive the log.\n const err = new Error(\n 'Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'\n );\n self.error(err.stack ?? err.message);\n return false;\n }\n\n if (typeof optionsOrLogLevel === 'number') {\n optionsOrLogLevel = {\n logLevel: optionsOrLogLevel,\n };\n }\n\n const oldLogger = getGlobal('diag');\n const newLogger = createLogLevelDiagLogger(\n optionsOrLogLevel.logLevel ?? DiagLogLevel.INFO,\n logger\n );\n // There already is an logger registered. We'll let it know before overwriting it.\n if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n const stack = new Error().stack ?? '<failed to generate stacktrace>';\n oldLogger.warn(`Current logger will be overwritten from ${stack}`);\n newLogger.warn(\n `Current logger will overwrite one already registered from ${stack}`\n );\n }\n\n return registerGlobal('diag', newLogger, self, true);\n };\n\n self.setLogger = setLogger;\n\n self.disable = () => {\n unregisterGlobal(API_NAME, self);\n };\n\n self.createComponentLogger = (options: ComponentLoggerOptions) => {\n return new DiagComponentLogger(options);\n };\n\n self.verbose = _logProxy('verbose');\n self.debug = _logProxy('debug');\n self.info = _logProxy('info');\n self.warn = _logProxy('warn');\n self.error = _logProxy('error');\n }\n\n public setLogger!: DiagLoggerApi['setLogger'];\n /**\n *\n */\n public createComponentLogger!: (\n options: ComponentLoggerOptions\n ) => DiagLogger;\n\n // DiagLogger implementation\n public verbose!: DiagLogFunction;\n public debug!: DiagLogFunction;\n public info!: DiagLogFunction;\n public warn!: DiagLogFunction;\n public error!: DiagLogFunction;\n\n /**\n * Unregister the global logger and return to Noop\n */\n public disable!: () => void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from './types';\n\n/** Get a key to uniquely identify a context value */\nexport function createContextKey(description: string) {\n // The specification states that for the same input, multiple calls should\n // return different keys. Due to the nature of the JS dependency management\n // system, this creates problems where multiple versions of some package\n // could hold different keys for the same property.\n //\n // Therefore, we use Symbol.for which returns the same key for the same input.\n return Symbol.for(description);\n}\n\nclass BaseContext implements Context {\n private _currentContext!: Map<symbol, unknown>;\n\n /**\n * Construct a new context which inherits values from an optional parent context.\n *\n * @param parentContext a context from which to inherit values\n */\n constructor(parentContext?: Map<symbol, unknown>) {\n // for minification\n const self = this;\n\n self._currentContext = parentContext ? new Map(parentContext) : new Map();\n\n self.getValue = (key: symbol) => self._currentContext.get(key);\n\n self.setValue = (key: symbol, value: unknown): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.set(key, value);\n return context;\n };\n\n self.deleteValue = (key: symbol): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.delete(key);\n return context;\n };\n }\n\n /**\n * Get a value from the context.\n *\n * @param key key which identifies a context value\n */\n public getValue!: (key: symbol) => unknown;\n\n /**\n * Create a new context which inherits from this context and has\n * the given key set to the given value.\n *\n * @param key context key for which to set the value\n * @param value value to set for the given key\n */\n public setValue!: (key: symbol, value: unknown) => Context;\n\n /**\n * Return a new context which inherits from this context but does\n * not contain a value for the given key.\n *\n * @param key context key for which to clear a value\n */\n public deleteValue!: (key: symbol) => Context;\n}\n\n/** The root context is used as the default parent context when there is no active context */\nexport const ROOT_CONTEXT: Context = new BaseContext();\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ROOT_CONTEXT } from './context';\nimport * as types from './types';\n\nexport class NoopContextManager implements types.ContextManager {\n active(): types.Context {\n return ROOT_CONTEXT;\n }\n\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n _context: types.Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n return fn.call(thisArg, ...args);\n }\n\n bind<T>(_context: types.Context, target: T): T {\n return target;\n }\n\n enable(): this {\n return this;\n }\n\n disable(): this {\n return this;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopContextManager } from '../context/NoopContextManager';\nimport { Context, ContextManager } from '../context/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'context';\nconst NOOP_CONTEXT_MANAGER = new NoopContextManager();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Context API\n */\nexport class ContextAPI {\n private static _instance?: ContextAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Context API */\n public static getInstance(): ContextAPI {\n if (!this._instance) {\n this._instance = new ContextAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current context manager.\n *\n * @returns true if the context manager was successfully registered, else false\n */\n public setGlobalContextManager(contextManager: ContextManager): boolean {\n return registerGlobal(API_NAME, contextManager, DiagAPI.instance());\n }\n\n /**\n * Get the currently active context\n */\n public active(): Context {\n return this._getContextManager().active();\n }\n\n /**\n * Execute a function with an active context\n *\n * @param context context to be active during function execution\n * @param fn function to execute in a context\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n public with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n return this._getContextManager().with(context, fn, thisArg, ...args);\n }\n\n /**\n * Bind a context to a target function or event emitter\n *\n * @param context context to bind to the event emitter or function. Defaults to the currently active context\n * @param target function or event emitter to bind\n */\n public bind<T>(context: Context, target: T): T {\n return this._getContextManager().bind(context, target);\n }\n\n private _getContextManager(): ContextManager {\n return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;\n }\n\n /** Disable and remove the global context manager */\n public disable() {\n this._getContextManager().disable();\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport interface SpanStatus {\n /** The status code of this message. */\n code: SpanStatusCode;\n /** A developer-facing error message. */\n message?: string;\n}\n\n/**\n * An enumeration of status codes.\n */\nexport enum SpanStatusCode {\n /**\n * The default status.\n */\n UNSET = 0,\n /**\n * The operation has been validated by an Application developer or\n * Operator to have completed successfully.\n */\n OK = 1,\n /**\n * The operation contains an error.\n */\n ERROR = 2,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { ContextAPI } from './api/context';\n/** Entrypoint for context API */\nexport const context = ContextAPI.getInstance();\n"],"mappings":"AAAA,OAAS,gBAAAA,OAAoB,iBAC7B,OAAS,sBAAAC,OAA0B,gBAanC,OACE,aAAAC,GACA,UAAAC,EACA,aAAAC,EACA,eAAAC,EACA,gBAAAC,EAEA,eAAAC,MACK,gBACP,OACE,kBAAAC,GACA,gBAAAC,EACA,kBAAAC,OAGK,KACP,OAA6B,oBAAAC,OAAwB,cACrD,OAAS,SAAAC,EAAO,YAAAC,OAAgB,SCbzB,IAAMC,EAAc,OAAO,YAAe,SAAW,WAAa,OCDlE,IAAMC,EAAU,QCCvB,IAAMC,EAAK,gCAkBL,SAAUC,GACdC,EAAkB,CAElB,IAAMC,EAAmB,IAAI,IAAY,CAACD,CAAU,CAAC,EAC/CE,EAAmB,IAAI,IAEvBC,EAAiBH,EAAW,MAAMF,CAAE,EAC1C,GAAI,CAACK,EAEH,OAAO,UAAA,CAAM,MAAA,EAAA,EAGf,IAAMC,EAAmB,CACvB,MAAO,CAACD,EAAe,CAAC,EACxB,MAAO,CAACA,EAAe,CAAC,EACxB,MAAO,CAACA,EAAe,CAAC,EACxB,WAAYA,EAAe,CAAC,GAI9B,GAAIC,EAAiB,YAAc,KACjC,OAAO,SAAsBC,EAAqB,CAChD,OAAOA,IAAk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,EAAQ,SAASkC,EAAU,sBAAuB,CAAE,OAD1D,yBACiE,CAAC,EACjF,GAAI,CAAC,MAAM,QAAQG,CAAM,GAAKA,EAAO,SAAW,EAC9C,MAAM,IAAI,MAAM,6DAA6D,EAE/EnC,EAAO,IAAI,oBAAqBmC,CAAM,CACxC,CACF,EACA,CACE,KAAM,oCACN,GAAI,MAAOrC,GAA2B,CACpC,IAAMgC,EAAS,0BACTK,EAAS,MAAMrC,EAAQ,SAASkC,EAAU,sBAAuB,CAAE,OAAAF,CAAO,CAAC,EAC3EkF,EAAc,MAAMlH,EAAQ,SAASkC,EAAU,sBAAuB,CAAE,OAAAG,CAAO,CAAC,EACtF,GAAI6E,IAAgBlF,EAClB,MAAM,IAAI,MACR,mDAAmDA,CAAM,WAAWkF,CAAW,GACjF,EAEFhH,EAAO,IAAI,gBAAiBgH,CAAW,CACzC,CACF,EACA,CACE,KAAM,6BACN,GAAI,MAAOlH,GAA2B,CACpC,GAAI,CAGF,GAAI,CADa,MAAM8D,GAAkB9D,EAD5B,2CACyC,EAEpD,MAAM,IAAI,MAAM,2BAA2B,EAE7CE,EAAO,IAAI,+BAA+B,CAC5C,OAASa,EAAgB,CACvB,IAAMC,EAAUD,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,EACrE,MAAAb,EAAO,MAAM,wCAAwCc,CAAO,EAAE,EACxDD,CACR,CACF,CACF,CACF,CACF,CACF,CACF,EACOoG,GAAQ7C","names":["createOpenAI","getProviderBaseURL","EventType","logger","ModelType","VECTOR_DIMS","safeReplacer","ServiceType","generateObject","generateText","JSONParseError","encodingForModel","fetch","FormData","_globalThis","VERSION","re","_makeCompatibilityCheck","ownVersion","acceptedVersions","rejectedVersions","myVersionMatch","ownVersionParsed","globalVersion","_reject","v","_accept","globalVersionMatch","globalVersionParsed","isCompatible","VERSION","major","VERSION","GLOBAL_OPENTELEMETRY_API_KEY","_global","_globalThis","registerGlobal","type","instance","diag","allowOverride","api","_a","err","getGlobal","globalVersion","isCompatible","_b","unregisterGlobal","DiagComponentLogger","props","args","_i","logProxy","logProxy","funcName","namespace","args","logger","getGlobal","__spreadArray","__read","DiagLogLevel","createLogLevelDiagLogger","maxLevel","logger","DiagLogLevel","_filterFunc","funcName","theLevel","theFunc","API_NAME","DiagAPI","_logProxy","funcName","args","_i","logger","getGlobal","__spreadArray","__read","self","setLogger","optionsOrLogLevel","DiagLogLevel","err","_a","oldLogger","newLogger","createLogLevelDiagLogger","_b","stack","_c","registerGlobal","unregisterGlobal","options","DiagComponentLogger","BaseContext","parentContext","self","key","value","context","ROOT_CONTEXT","NoopContextManager","ROOT_CONTEXT","_context","fn","thisArg","args","_i","__spreadArray","__read","target","API_NAME","NOOP_CONTEXT_MANAGER","NoopContextManager","ContextAPI","contextManager","registerGlobal","DiagAPI","context","fn","thisArg","args","_i","_a","__spreadArray","__read","target","getGlobal","unregisterGlobal","SpanStatusCode","context","ContextAPI","getTracer","runtime","availableServices","logger","ServiceType","instrumentationService","startLlmSpan","spanName","attributes","fn","tracer","activeContext","context","span","result","SpanStatusCode","error","message","getSetting","key","defaultValue","getBaseURL","defaultBaseURL","getProviderBaseURL","getEmbeddingBaseURL","embeddingURL","getApiKey","getSmallModel","getLargeModel","createOpenAIClient","createOpenAI","tokenizeText","model","prompt","modelName","ModelType","encodingForModel","detokenizeText","tokens","generateObjectByModelType","params","modelType","getModelFn","openai","temperature","schemaPresent","safeReplacer","object","usage","generateObject","getJsonRepairFunction","emitModelUsageEvent","JSONParseError","repairedJsonString","repairedObject","repairParseError","exception","errMsg","text","cleanedText","jsonError","type","EventType","fetchTextToSpeech","apiKey","voice","instructions","baseURL","res","fetch","err","openaiPlugin","_config","response","fetchError","e","embeddingModelName","embeddingDimension","VECTOR_DIMS","errorMsg","testVector","fallbackVector","emptyVector","embeddingBaseURL","rawResponseBody","errorVector","data","embedding","_runtime","stopSequences","openaiResponse","generateText","maxTokens","frequencyPenalty","presencePenalty","n","size","typedData","imageUrl","promptText","messages","typedResult","content","title","description","processedResult","audioBuffer","formData","FormData","processedText","ttsModelName","speechStream","image","arrayBuffer","transcription","decodedText","index_default"]}
1
+ {"version":3,"sources":["../src/index.ts","../../../node_modules/@opentelemetry/api/src/platform/node/globalThis.ts","../../../node_modules/@opentelemetry/api/src/version.ts","../../../node_modules/@opentelemetry/api/src/internal/semver.ts","../../../node_modules/@opentelemetry/api/src/internal/global-utils.ts","../../../node_modules/@opentelemetry/api/src/diag/ComponentLogger.ts","../../../node_modules/@opentelemetry/api/src/diag/types.ts","../../../node_modules/@opentelemetry/api/src/diag/internal/logLevelLogger.ts","../../../node_modules/@opentelemetry/api/src/api/diag.ts","../../../node_modules/@opentelemetry/api/src/context/context.ts","../../../node_modules/@opentelemetry/api/src/context/NoopContextManager.ts","../../../node_modules/@opentelemetry/api/src/api/context.ts","../../../node_modules/@opentelemetry/api/src/trace/status.ts","../../../node_modules/@opentelemetry/api/src/context-api.ts"],"sourcesContent":["import { createOpenAI } from '@ai-sdk/openai';\nimport { getProviderBaseURL } from '@elizaos/core';\nimport type {\n IAgentRuntime,\n ImageDescriptionParams,\n ModelTypeName,\n ObjectGenerationParams,\n Plugin,\n ServiceTypeName,\n TextEmbeddingParams,\n TokenizeTextParams,\n DetokenizeTextParams,\n GenerateTextParams,\n} from '@elizaos/core';\nimport {\n EventType,\n logger,\n ModelType,\n VECTOR_DIMS,\n safeReplacer,\n type InstrumentationService,\n ServiceType,\n} from '@elizaos/core';\nimport {\n generateObject,\n generateText,\n JSONParseError,\n type JSONValue,\n type LanguageModelUsage,\n} from 'ai';\nimport { type TiktokenModel, encodingForModel } from 'js-tiktoken';\nimport { fetch, FormData } from 'undici';\nimport { SpanStatusCode, trace, type Span, context } from '@opentelemetry/api';\n\n/**\n * Helper function to get tracer if instrumentation is enabled\n */\nfunction getTracer(runtime: IAgentRuntime) {\n const availableServices = Array.from(runtime.getAllServices().keys());\n logger.debug(`[getTracer] Available services: ${JSON.stringify(availableServices)}`);\n logger.debug(`[getTracer] Attempting to get service with key: ${ServiceType.INSTRUMENTATION}`);\n\n const instrumentationService = runtime.getService<InstrumentationService>(\n ServiceType.INSTRUMENTATION\n );\n\n if (!instrumentationService) {\n logger.warn(`[getTracer] Service ${ServiceType.INSTRUMENTATION} not found in runtime.`);\n return null;\n }\n\n if (!instrumentationService.isEnabled()) {\n logger.debug('[getTracer] Instrumentation service found but is disabled.');\n return null;\n }\n\n logger.debug('[getTracer] Successfully retrieved enabled instrumentation service.');\n return instrumentationService.getTracer('eliza.llm.openai');\n}\n\n/**\n * Helper function to start an LLM span\n */\nasync function startLlmSpan<T>(\n runtime: IAgentRuntime,\n spanName: string,\n attributes: Record<string, string | number | boolean>,\n fn: (span: Span) => Promise<T>\n): Promise<T> {\n const tracer = getTracer(runtime);\n if (!tracer) {\n const dummySpan = {\n setAttribute: () => {},\n setAttributes: () => {},\n addEvent: () => {},\n recordException: () => {},\n setStatus: () => {},\n end: () => {},\n spanContext: () => ({ traceId: '', spanId: '', traceFlags: 0 }),\n } as unknown as Span;\n return fn(dummySpan);\n }\n\n // Get active context to ensure proper nesting\n const activeContext = context.active();\n\n return tracer.startActiveSpan(spanName, { attributes }, activeContext, async (span: Span) => {\n try {\n const result = await fn(span);\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n return result;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n span.recordException(error as Error);\n span.setStatus({ code: SpanStatusCode.ERROR, message });\n span.end();\n throw error;\n }\n });\n}\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(runtime, 'OPENAI_BASE_URL', 'https://api.openai.com/v1');\n logger.debug(`[OpenAI] Default base URL: ${defaultBaseURL}`);\n return getProviderBaseURL(runtime, 'openai', defaultBaseURL);\n}\n\n/**\n * Retrieves the OpenAI API base URL for embeddings, falling back to the general base URL.\n *\n * @returns The resolved base URL for OpenAI embedding requests.\n */\nfunction getEmbeddingBaseURL(runtime: IAgentRuntime): string {\n const embeddingURL = getSetting(runtime, 'OPENAI_EMBEDDING_URL');\n if (embeddingURL) {\n logger.debug(`[OpenAI] Using specific embedding base URL: ${embeddingURL}`);\n return embeddingURL;\n }\n logger.debug('[OpenAI] Falling back to general base URL for embeddings.');\n return getBaseURL(runtime);\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, 'OPENAI_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, 'OPENAI_SMALL_MODEL') ?? getSetting(runtime, 'SMALL_MODEL', 'gpt-4o-mini')\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 getSetting(runtime, 'OPENAI_LARGE_MODEL') ?? getSetting(runtime, 'LARGE_MODEL', 'gpt-4o');\n}\n\n/**\n * Create an OpenAI client with proper configuration\n *\n * @param runtime The runtime context\n * @returns Configured OpenAI client\n */\nfunction createOpenAIClient(runtime: IAgentRuntime) {\n return createOpenAI({\n apiKey: getApiKey(runtime),\n baseURL: getBaseURL(runtime),\n });\n}\n\n/**\n * Asynchronously tokenizes the given text based on the specified model and prompt.\n *\n * @param {ModelTypeName} model - The type of model to use for tokenization.\n * @param {string} prompt - The text prompt to tokenize.\n * @returns {number[]} - An array of tokens representing the encoded prompt.\n */\nasync function tokenizeText(model: ModelTypeName, prompt: string) {\n const modelName =\n model === ModelType.TEXT_SMALL\n ? (process.env.OPENAI_SMALL_MODEL ?? process.env.SMALL_MODEL ?? 'gpt-4o-mini')\n : (process.env.LARGE_MODEL ?? 'gpt-4o');\n const encoding = encodingForModel(modelName as TiktokenModel);\n const tokens = encoding.encode(prompt);\n return tokens;\n}\n\n/**\n * Detokenize a sequence of tokens back into text using the specified model.\n *\n * @param {ModelTypeName} model - The type of model to use for detokenization.\n * @param {number[]} tokens - The sequence of tokens to detokenize.\n * @returns {string} The detokenized text.\n */\nasync function detokenizeText(model: ModelTypeName, tokens: number[]) {\n const modelName =\n model === ModelType.TEXT_SMALL\n ? (process.env.OPENAI_SMALL_MODEL ?? process.env.SMALL_MODEL ?? 'gpt-4o-mini')\n : (process.env.OPENAI_LARGE_MODEL ?? process.env.LARGE_MODEL ?? 'gpt-4o');\n const encoding = encodingForModel(modelName as TiktokenModel);\n return encoding.decode(tokens);\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 openai = createOpenAIClient(runtime);\n const modelName = getModelFn(runtime);\n logger.log(`[OpenAI] Using ${modelType} model: ${modelName}`);\n const temperature = params.temperature ?? 0;\n const schemaPresent = !!params.schema;\n\n // --- Start Instrumentation ---\n const attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'object_generation',\n 'llm.request.model': modelName,\n 'llm.request.temperature': temperature,\n 'llm.request.schema_present': schemaPresent,\n };\n\n return startLlmSpan(runtime, 'LLM.generateObject', attributes, async (span) => {\n span.addEvent('llm.prompt', { 'prompt.content': params.prompt });\n if (schemaPresent) {\n span.addEvent('llm.request.schema', {\n schema: JSON.stringify(params.schema, safeReplacer()),\n });\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: openai.languageModel(modelName),\n output: 'no-schema',\n prompt: params.prompt,\n temperature: temperature,\n experimental_repairText: getJsonRepairFunction(),\n });\n\n span.addEvent('llm.response.processed', {\n 'response.object': JSON.stringify(object, safeReplacer()),\n });\n\n if (usage) {\n span.setAttributes({\n 'llm.usage.prompt_tokens': usage.promptTokens,\n 'llm.usage.completion_tokens': usage.completionTokens,\n 'llm.usage.total_tokens': usage.totalTokens,\n });\n emitModelUsageEvent(runtime, modelType as ModelTypeName, params.prompt, usage);\n }\n return object;\n } catch (error: unknown) {\n if (error instanceof JSONParseError) {\n logger.error(`[generateObject] Failed to parse JSON: ${error.message}`);\n span.recordException(error);\n span.addEvent('llm.error.json_parse', {\n 'error.message': error.message,\n 'error.text': error.text,\n });\n\n span.addEvent('llm.repair.attempt');\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 span.addEvent('llm.repair.success', {\n repaired_object: JSON.stringify(repairedObject, safeReplacer()),\n });\n logger.info('[generateObject] Successfully repaired JSON.');\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'JSON parsing failed but was repaired',\n });\n return repairedObject;\n } catch (repairParseError: unknown) {\n const message =\n repairParseError instanceof Error\n ? repairParseError.message\n : String(repairParseError);\n logger.error(`[generateObject] Failed to parse repaired JSON: ${message}`);\n const exception =\n repairParseError instanceof Error ? repairParseError : new Error(message);\n span.recordException(exception);\n span.addEvent('llm.repair.parse_error', {\n 'error.message': message,\n });\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `JSON repair failed: ${message}`,\n });\n throw repairParseError;\n }\n } else {\n const errMsg = error instanceof Error ? error.message : String(error);\n logger.error('[generateObject] JSON repair failed.');\n span.addEvent('llm.repair.failed');\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `JSON repair failed: ${errMsg}`,\n });\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 span.recordException(exception);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: message,\n });\n throw error;\n }\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 = 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: 'openai',\n type,\n prompt,\n tokens: {\n prompt: usage.promptTokens,\n completion: usage.completionTokens,\n total: usage.totalTokens,\n },\n });\n}\n\n/**\n * function for text-to-speech\n */\nasync function fetchTextToSpeech(runtime: IAgentRuntime, text: string) {\n const apiKey = getApiKey(runtime);\n const model = getSetting(runtime, 'OPENAI_TTS_MODEL', 'gpt-4o-mini-tts');\n const voice = getSetting(runtime, 'OPENAI_TTS_VOICE', 'nova');\n const instructions = getSetting(runtime, 'OPENAI_TTS_INSTRUCTIONS', '');\n const baseURL = getBaseURL(runtime);\n\n try {\n const res = await fetch(`${baseURL}/audio/speech`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n model,\n voice,\n input: text,\n ...(instructions && { instructions }),\n }),\n });\n\n if (!res.ok) {\n const err = await res.text();\n throw new Error(`OpenAI TTS error ${res.status}: ${err}`);\n }\n\n return res.body;\n } catch (err: unknown) {\n const message = err instanceof Error ? err.message : String(err);\n throw new Error(`Failed to fetch speech from OpenAI TTS: ${message}`);\n }\n}\n\n/**\n * Defines the OpenAI plugin with its name, description, and configuration options.\n * @type {Plugin}\n */\nexport const openaiPlugin: Plugin = {\n name: 'openai',\n description: 'OpenAI plugin',\n config: {\n OPENAI_API_KEY: process.env.OPENAI_API_KEY,\n OPENAI_BASE_URL: process.env.OPENAI_BASE_URL,\n OPENAI_SMALL_MODEL: process.env.OPENAI_SMALL_MODEL,\n OPENAI_LARGE_MODEL: process.env.OPENAI_LARGE_MODEL,\n SMALL_MODEL: process.env.SMALL_MODEL,\n LARGE_MODEL: process.env.LARGE_MODEL,\n OPENAI_EMBEDDING_MODEL: process.env.OPENAI_EMBEDDING_MODEL,\n OPENAI_EMBEDDING_URL: process.env.OPENAI_EMBEDDING_URL,\n OPENAI_EMBEDDING_DIMENSIONS: process.env.OPENAI_EMBEDDING_DIMENSIONS,\n },\n async init(_config, runtime) {\n try {\n if (!getApiKey(runtime)) {\n logger.warn(\n 'OPENAI_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(`OpenAI API key validation failed: ${response.statusText}`);\n logger.warn('OpenAI functionality will be limited until a valid API key is provided');\n } else {\n logger.log('OpenAI API key validated successfully');\n }\n } catch (fetchError: unknown) {\n const message = fetchError instanceof Error ? fetchError.message : String(fetchError);\n logger.warn(`Error validating OpenAI API key: ${message}`);\n logger.warn('OpenAI functionality will be limited until a valid API key is provided');\n }\n } catch (error: unknown) {\n const message =\n (error as { errors?: Array<{ message: string }> })?.errors\n ?.map((e) => e.message)\n .join(', ') || (error instanceof Error ? error.message : String(error));\n logger.warn(\n `OpenAI plugin configuration issue: ${message} - You need to configure the OPENAI_API_KEY in your environment variables`\n );\n }\n },\n models: {\n [ModelType.TEXT_EMBEDDING]: async (\n runtime: IAgentRuntime,\n params: TextEmbeddingParams | string | null\n ): Promise<number[]> => {\n const embeddingModelName = getSetting(\n runtime,\n 'OPENAI_EMBEDDING_MODEL',\n 'text-embedding-3-small'\n );\n const embeddingDimension = Number.parseInt(\n getSetting(runtime, 'OPENAI_EMBEDDING_DIMENSIONS', '1536') || '1536',\n 10\n ) as (typeof VECTOR_DIMS)[keyof typeof VECTOR_DIMS];\n\n // Added log for specific embedding model\n logger.debug(\n `[OpenAI] Using embedding model: ${embeddingModelName} with dimension: ${embeddingDimension}`\n );\n\n if (!Object.values(VECTOR_DIMS).includes(embeddingDimension)) {\n const errorMsg = `Invalid embedding dimension: ${embeddingDimension}. Must be one of: ${Object.values(VECTOR_DIMS).join(', ')}`;\n logger.error(errorMsg);\n throw new Error(errorMsg);\n }\n if (params === null) {\n logger.debug('Creating test embedding for initialization');\n const testVector = Array(embeddingDimension).fill(0);\n testVector[0] = 0.1;\n return testVector;\n }\n let text: string;\n if (typeof params === 'string') {\n text = params;\n } else if (typeof params === 'object' && params.text) {\n text = params.text;\n } else {\n logger.warn('Invalid input format for embedding');\n const fallbackVector = Array(embeddingDimension).fill(0);\n fallbackVector[0] = 0.2;\n return fallbackVector;\n }\n if (!text.trim()) {\n logger.warn('Empty text for embedding');\n const emptyVector = Array(embeddingDimension).fill(0);\n emptyVector[0] = 0.3;\n return emptyVector;\n }\n\n const attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'embedding',\n 'llm.request.model': embeddingModelName,\n 'llm.request.embedding.dimensions': embeddingDimension,\n 'input.text.length': text.length,\n };\n\n return startLlmSpan(runtime, 'LLM.embedding', attributes, async (span) => {\n span.addEvent('llm.prompt', { 'prompt.content': text });\n\n const embeddingBaseURL = getEmbeddingBaseURL(runtime);\n const apiKey = getApiKey(runtime);\n\n if (!apiKey) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'OpenAI API key not configured',\n });\n throw new Error('OpenAI API key not configured');\n }\n\n try {\n const response = await fetch(`${embeddingBaseURL}/embeddings`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n model: embeddingModelName,\n input: text,\n }),\n });\n\n const responseClone = response.clone();\n const rawResponseBody = await responseClone.text();\n span.addEvent('llm.response.raw', {\n 'response.body': rawResponseBody,\n });\n\n if (!response.ok) {\n logger.error(`OpenAI API error: ${response.status} - ${response.statusText}`);\n span.setAttributes({ 'error.api.status': response.status });\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `OpenAI API error: ${response.status} - ${response.statusText}. Response: ${rawResponseBody}`,\n });\n const errorVector = Array(embeddingDimension).fill(0);\n errorVector[0] = 0.4;\n return errorVector;\n }\n\n const data = (await response.json()) as {\n data: [{ embedding: number[] }];\n usage?: { prompt_tokens: number; total_tokens: number };\n };\n\n if (!data?.data?.[0]?.embedding) {\n logger.error('API returned invalid structure');\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'API returned invalid structure',\n });\n const errorVector = Array(embeddingDimension).fill(0);\n errorVector[0] = 0.5;\n return errorVector;\n }\n\n const embedding = data.data[0].embedding;\n span.setAttribute('llm.response.embedding.vector_length', embedding.length);\n\n if (data.usage) {\n span.setAttributes({\n 'llm.usage.prompt_tokens': data.usage.prompt_tokens,\n 'llm.usage.total_tokens': data.usage.total_tokens,\n });\n\n const usage = {\n promptTokens: data.usage.prompt_tokens,\n completionTokens: 0,\n totalTokens: data.usage.total_tokens,\n };\n\n emitModelUsageEvent(runtime, ModelType.TEXT_EMBEDDING, text, usage);\n }\n\n logger.log(`Got valid embedding with length ${embedding.length}`);\n return embedding;\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error generating embedding: ${message}`);\n const exception = error instanceof Error ? error : new Error(message);\n span.recordException(exception);\n span.setStatus({ code: SpanStatusCode.ERROR, message: message });\n const errorVector = Array(embeddingDimension).fill(0);\n errorVector[0] = 0.6;\n return errorVector;\n }\n });\n },\n [ModelType.TEXT_TOKENIZER_ENCODE]: async (\n _runtime,\n { prompt, modelType = ModelType.TEXT_LARGE }: TokenizeTextParams\n ) => {\n return await tokenizeText(modelType ?? ModelType.TEXT_LARGE, prompt);\n },\n [ModelType.TEXT_TOKENIZER_DECODE]: async (\n _runtime,\n { tokens, modelType = ModelType.TEXT_LARGE }: DetokenizeTextParams\n ) => {\n return await detokenizeText(modelType ?? ModelType.TEXT_LARGE, tokens);\n },\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 openai = createOpenAIClient(runtime);\n const modelName = getSmallModel(runtime);\n\n logger.log(`[OpenAI] Using TEXT_SMALL model: ${modelName}`);\n logger.log(prompt);\n\n const attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'completion',\n 'llm.request.model': modelName,\n 'llm.request.temperature': temperature,\n 'llm.request.max_tokens': max_response_length,\n 'llm.request.frequency_penalty': frequency_penalty,\n 'llm.request.presence_penalty': presence_penalty,\n 'llm.request.stop_sequences': JSON.stringify(stopSequences),\n };\n\n return startLlmSpan(runtime, 'LLM.generateText', attributes, async (span) => {\n span.addEvent('llm.prompt', { 'prompt.content': prompt });\n\n const { text: openaiResponse, usage } = await generateText({\n model: openai.languageModel(modelName),\n prompt: prompt,\n system: runtime.character.system ?? undefined,\n temperature: temperature,\n maxTokens: max_response_length,\n frequencyPenalty: frequency_penalty,\n presencePenalty: presence_penalty,\n stopSequences: stopSequences,\n });\n\n span.setAttribute('llm.response.processed.length', openaiResponse.length);\n span.addEvent('llm.response.processed', {\n 'response.content':\n openaiResponse.substring(0, 200) + (openaiResponse.length > 200 ? '...' : ''),\n });\n\n if (usage) {\n span.setAttributes({\n 'llm.usage.prompt_tokens': usage.promptTokens,\n 'llm.usage.completion_tokens': usage.completionTokens,\n 'llm.usage.total_tokens': usage.totalTokens,\n });\n emitModelUsageEvent(runtime, ModelType.TEXT_SMALL, prompt, usage);\n }\n\n return openaiResponse;\n });\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 openai = createOpenAIClient(runtime);\n const modelName = getLargeModel(runtime);\n\n logger.log(`[OpenAI] Using TEXT_LARGE model: ${modelName}`);\n logger.log(prompt);\n\n const attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'completion',\n 'llm.request.model': modelName,\n 'llm.request.temperature': temperature,\n 'llm.request.max_tokens': maxTokens,\n 'llm.request.frequency_penalty': frequencyPenalty,\n 'llm.request.presence_penalty': presencePenalty,\n 'llm.request.stop_sequences': JSON.stringify(stopSequences),\n };\n\n return startLlmSpan(runtime, 'LLM.generateText', attributes, async (span) => {\n span.addEvent('llm.prompt', { 'prompt.content': prompt });\n\n const { text: openaiResponse, usage } = await generateText({\n model: openai.languageModel(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\n span.setAttribute('llm.response.processed.length', openaiResponse.length);\n span.addEvent('llm.response.processed', {\n 'response.content':\n openaiResponse.substring(0, 200) + (openaiResponse.length > 200 ? '...' : ''),\n });\n\n if (usage) {\n span.setAttributes({\n 'llm.usage.prompt_tokens': usage.promptTokens,\n 'llm.usage.completion_tokens': usage.completionTokens,\n 'llm.usage.total_tokens': usage.totalTokens,\n });\n emitModelUsageEvent(runtime, ModelType.TEXT_LARGE, prompt, usage);\n }\n\n return openaiResponse;\n });\n },\n [ModelType.IMAGE]: async (\n runtime: IAgentRuntime,\n params: {\n prompt: string;\n n?: number;\n size?: string;\n }\n ) => {\n const n = params.n || 1;\n const size = params.size || '1024x1024';\n const prompt = params.prompt;\n const modelName = 'dall-e-3'; // Default DALL-E model\n logger.log(`[OpenAI] Using IMAGE model: ${modelName}`);\n\n const attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'image_generation',\n 'llm.request.image.size': size,\n 'llm.request.image.count': n,\n };\n\n return startLlmSpan(runtime, 'LLM.imageGeneration', attributes, async (span) => {\n span.addEvent('llm.prompt', { 'prompt.content': prompt });\n\n const baseURL = getBaseURL(runtime);\n const apiKey = getApiKey(runtime);\n\n if (!apiKey) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'OpenAI API key not configured',\n });\n throw new Error('OpenAI API key not configured');\n }\n\n try {\n const response = await fetch(`${baseURL}/images/generations`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n prompt: prompt,\n n: n,\n size: size,\n }),\n });\n\n const responseClone = response.clone();\n const rawResponseBody = await responseClone.text();\n span.addEvent('llm.response.raw', {\n 'response.body': rawResponseBody,\n });\n\n if (!response.ok) {\n span.setAttributes({ 'error.api.status': response.status });\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `Failed to generate image: ${response.statusText}. Response: ${rawResponseBody}`,\n });\n throw new Error(`Failed to generate image: ${response.statusText}`);\n }\n\n const data = await response.json();\n const typedData = data as { data: { url: string }[] };\n\n span.addEvent('llm.response.processed', {\n 'response.urls': JSON.stringify(typedData.data),\n });\n\n return typedData.data;\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n const exception = error instanceof Error ? error : new Error(message);\n span.recordException(exception);\n span.setStatus({ code: SpanStatusCode.ERROR, message: message });\n throw error;\n }\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 = 'gpt-4o-mini';\n logger.log(`[OpenAI] Using IMAGE_DESCRIPTION model: ${modelName}`);\n const maxTokens = 300;\n\n if (typeof params === 'string') {\n imageUrl = params;\n promptText = '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 attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'chat',\n 'llm.request.model': modelName,\n 'llm.request.max_tokens': maxTokens,\n 'llm.request.image.url': imageUrl,\n };\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 return startLlmSpan(runtime, 'LLM.imageDescription', attributes, async (span) => {\n span.addEvent('llm.prompt', {\n 'prompt.content': JSON.stringify(messages, safeReplacer()),\n });\n\n const baseURL = getBaseURL(runtime);\n const apiKey = getApiKey(runtime);\n\n if (!apiKey) {\n logger.error('OpenAI API key not set');\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'OpenAI API key not configured',\n });\n return {\n title: 'Failed to analyze image',\n description: 'API key not configured',\n };\n }\n\n try {\n const response = await fetch(`${baseURL}/chat/completions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n model: modelName,\n messages: messages,\n max_tokens: maxTokens,\n }),\n });\n\n const responseClone = response.clone();\n const rawResponseBody = await responseClone.text();\n span.addEvent('llm.response.raw', {\n 'response.body': rawResponseBody,\n });\n\n if (!response.ok) {\n span.setAttributes({ 'error.api.status': response.status });\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `OpenAI API error: ${response.status}. Response: ${rawResponseBody}`,\n });\n throw new Error(`OpenAI API error: ${response.status}`);\n }\n\n const result: unknown = await response.json();\n\n type OpenAIResponseType = {\n choices?: Array<{\n message?: { content?: string };\n finish_reason?: string;\n }>;\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n };\n };\n\n const typedResult = result as OpenAIResponseType;\n const content = typedResult.choices?.[0]?.message?.content;\n\n if (typedResult.usage) {\n span.setAttributes({\n 'llm.usage.prompt_tokens': typedResult.usage.prompt_tokens,\n 'llm.usage.completion_tokens': typedResult.usage.completion_tokens,\n 'llm.usage.total_tokens': typedResult.usage.total_tokens,\n });\n\n emitModelUsageEvent(\n runtime,\n ModelType.IMAGE_DESCRIPTION,\n typeof params === 'string' ? params : params.prompt || '',\n {\n promptTokens: typedResult.usage.prompt_tokens,\n completionTokens: typedResult.usage.completion_tokens,\n totalTokens: typedResult.usage.total_tokens,\n }\n );\n }\n if (typedResult.choices?.[0]?.finish_reason) {\n span.setAttribute('llm.response.finish_reason', typedResult.choices[0].finish_reason);\n }\n\n if (!content) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'No content in API response',\n });\n return {\n title: 'Failed to analyze image',\n description: 'No response from API',\n };\n }\n\n const titleMatch = content.match(/title[:\\s]+(.+?)(?:\\n|$)/i);\n const title = titleMatch?.[1]?.trim() || 'Image Analysis';\n const description = content.replace(/title[:\\s]+(.+?)(?:\\n|$)/i, '').trim();\n\n const processedResult = { title, description };\n span.addEvent('llm.response.processed', {\n 'response.object': JSON.stringify(processedResult, safeReplacer()),\n });\n\n return processedResult;\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error analyzing image: ${message}`);\n const exception = error instanceof Error ? error : new Error(message);\n span.recordException(exception);\n span.setStatus({ code: SpanStatusCode.ERROR, message: message });\n return {\n title: 'Failed to analyze image',\n description: `Error: ${message}`,\n };\n }\n });\n },\n [ModelType.TRANSCRIPTION]: async (runtime: IAgentRuntime, audioBuffer: Buffer) => {\n logger.log('audioBuffer', audioBuffer);\n\n const modelName = 'whisper-1';\n logger.log(`[OpenAI] Using TRANSCRIPTION model: ${modelName}`);\n const attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'transcription',\n 'llm.request.model': modelName,\n 'llm.request.audio.input_size_bytes': audioBuffer?.length || 0,\n };\n\n return startLlmSpan(runtime, 'LLM.transcription', attributes, async (span) => {\n span.addEvent('llm.prompt', {\n 'prompt.info': 'Audio buffer for transcription',\n });\n\n const baseURL = getBaseURL(runtime);\n const apiKey = getApiKey(runtime);\n\n if (!apiKey) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'OpenAI API key not configured',\n });\n throw new Error('OpenAI API key not configured - Cannot make request');\n }\n if (!audioBuffer || audioBuffer.length === 0) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: 'Audio buffer is empty or invalid',\n });\n throw new Error('Audio buffer is empty or invalid for transcription');\n }\n\n const formData = new FormData();\n formData.append('file', new Blob([audioBuffer]), 'recording.mp3');\n formData.append('model', 'whisper-1');\n\n try {\n const response = await fetch(`${baseURL}/audio/transcriptions`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n },\n body: formData,\n });\n\n const responseClone = response.clone();\n const rawResponseBody = await responseClone.text();\n span.addEvent('llm.response.raw', {\n 'response.body': rawResponseBody,\n });\n\n logger.log('response', response);\n\n if (!response.ok) {\n span.setAttributes({ 'error.api.status': response.status });\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: `Failed to transcribe audio: ${response.statusText}. Response: ${rawResponseBody}`,\n });\n throw new Error(`Failed to transcribe audio: ${response.statusText}`);\n }\n\n const data = (await response.json()) as { text: string };\n const processedText = data.text;\n\n span.setAttribute('llm.response.processed.length', processedText.length);\n span.addEvent('llm.response.processed', {\n 'response.text': processedText,\n });\n\n return processedText;\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n const exception = error instanceof Error ? error : new Error(message);\n span.recordException(exception);\n span.setStatus({ code: SpanStatusCode.ERROR, message: message });\n throw error;\n }\n });\n },\n [ModelType.TEXT_TO_SPEECH]: async (runtime: IAgentRuntime, text: string) => {\n const ttsModelName = getSetting(runtime, 'OPENAI_TTS_MODEL', 'gpt-4o-mini-tts');\n const attributes = {\n 'llm.vendor': 'OpenAI',\n 'llm.request.type': 'tts',\n 'llm.request.model': ttsModelName,\n 'input.text.length': text.length,\n };\n return startLlmSpan(runtime, 'LLM.tts', attributes, async (span) => {\n logger.log(`[OpenAI] Using TEXT_TO_SPEECH model: ${ttsModelName}`);\n span.addEvent('llm.prompt', { 'prompt.content': text });\n try {\n const speechStream = await fetchTextToSpeech(runtime, text);\n span.addEvent('llm.response.success', {\n info: 'Speech stream generated',\n });\n return speechStream;\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n const exception = error instanceof Error ? error : new Error(message);\n span.recordException(exception);\n span.setStatus({ code: SpanStatusCode.ERROR, message: message });\n throw error;\n }\n });\n },\n [ModelType.OBJECT_SMALL]: async (runtime: IAgentRuntime, params: ObjectGenerationParams) => {\n return generateObjectByModelType(runtime, params, ModelType.OBJECT_SMALL, getSmallModel);\n },\n [ModelType.OBJECT_LARGE]: async (runtime: IAgentRuntime, params: ObjectGenerationParams) => {\n return generateObjectByModelType(runtime, params, ModelType.OBJECT_LARGE, getLargeModel);\n },\n },\n tests: [\n {\n name: 'openai_plugin_tests',\n tests: [\n {\n name: 'openai_test_url_and_api_key_validation',\n fn: async (runtime: IAgentRuntime) => {\n const baseURL = getBaseURL(runtime);\n const response = await fetch(`${baseURL}/models`, {\n headers: {\n Authorization: `Bearer ${getApiKey(runtime)}`,\n },\n });\n const data = await response.json();\n logger.log('Models Available:', (data as { data?: unknown[] })?.data?.length ?? 'N/A');\n if (!response.ok) {\n throw new Error(`Failed to validate OpenAI API key: ${response.statusText}`);\n }\n },\n },\n {\n name: 'openai_test_text_embedding',\n fn: async (runtime: IAgentRuntime) => {\n try {\n const embedding = await runtime.useModel(ModelType.TEXT_EMBEDDING, {\n text: 'Hello, world!',\n });\n logger.log('embedding', embedding);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error in test_text_embedding: ${message}`);\n throw error;\n }\n },\n },\n {\n name: 'openai_test_text_large',\n fn: async (runtime: IAgentRuntime) => {\n try {\n const text = await runtime.useModel(ModelType.TEXT_LARGE, {\n prompt: 'What is the nature of reality in 10 words?',\n });\n if (text.length === 0) {\n throw new Error('Failed to generate text');\n }\n logger.log('generated with test_text_large:', text);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error in test_text_large: ${message}`);\n throw error;\n }\n },\n },\n {\n name: 'openai_test_text_small',\n fn: async (runtime: IAgentRuntime) => {\n try {\n const text = await runtime.useModel(ModelType.TEXT_SMALL, {\n prompt: 'What is the nature of reality in 10 words?',\n });\n if (text.length === 0) {\n throw new Error('Failed to generate text');\n }\n logger.log('generated with test_text_small:', text);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error in test_text_small: ${message}`);\n throw error;\n }\n },\n },\n {\n name: 'openai_test_image_generation',\n fn: async (runtime: IAgentRuntime) => {\n logger.log('openai_test_image_generation');\n try {\n const image = await runtime.useModel(ModelType.IMAGE, {\n prompt: 'A beautiful sunset over a calm ocean',\n n: 1,\n size: '1024x1024',\n });\n logger.log('generated with test_image_generation:', image);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error in test_image_generation: ${message}`);\n throw error;\n }\n },\n },\n {\n name: 'image-description',\n fn: async (runtime: IAgentRuntime) => {\n try {\n logger.log('openai_test_image_description');\n try {\n const result = await runtime.useModel(\n ModelType.IMAGE_DESCRIPTION,\n 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/1c/Vitalik_Buterin_TechCrunch_London_2015_%28cropped%29.jpg/537px-Vitalik_Buterin_TechCrunch_London_2015_%28cropped%29.jpg'\n );\n\n if (\n result &&\n typeof result === 'object' &&\n 'title' in result &&\n 'description' in result\n ) {\n logger.log('Image description:', result);\n } else {\n logger.error('Invalid image description result format:', result);\n }\n } catch (e: unknown) {\n const message = e instanceof Error ? e.message : String(e);\n logger.error(`Error in image description test: ${message}`);\n }\n } catch (e: unknown) {\n const message = e instanceof Error ? e.message : String(e);\n logger.error(`Error in openai_test_image_description: ${message}`);\n }\n },\n },\n {\n name: 'openai_test_transcription',\n fn: async (runtime: IAgentRuntime) => {\n logger.log('openai_test_transcription');\n try {\n const response = await fetch(\n 'https://upload.wikimedia.org/wikipedia/en/4/40/Chris_Benoit_Voice_Message.ogg'\n );\n const arrayBuffer = await response.arrayBuffer();\n const transcription = await runtime.useModel(\n ModelType.TRANSCRIPTION,\n Buffer.from(new Uint8Array(arrayBuffer))\n );\n logger.log('generated with test_transcription:', transcription);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error in test_transcription: ${message}`);\n throw error;\n }\n },\n },\n {\n name: 'openai_test_text_tokenizer_encode',\n fn: async (runtime: IAgentRuntime) => {\n const prompt = 'Hello tokenizer encode!';\n const tokens = await runtime.useModel(ModelType.TEXT_TOKENIZER_ENCODE, { prompt });\n if (!Array.isArray(tokens) || tokens.length === 0) {\n throw new Error('Failed to tokenize text: expected non-empty array of tokens');\n }\n logger.log('Tokenized output:', tokens);\n },\n },\n {\n name: 'openai_test_text_tokenizer_decode',\n fn: async (runtime: IAgentRuntime) => {\n const prompt = 'Hello tokenizer decode!';\n const tokens = await runtime.useModel(ModelType.TEXT_TOKENIZER_ENCODE, { prompt });\n const decodedText = await runtime.useModel(ModelType.TEXT_TOKENIZER_DECODE, { tokens });\n if (decodedText !== prompt) {\n throw new Error(\n `Decoded text does not match original. Expected \"${prompt}\", got \"${decodedText}\"`\n );\n }\n logger.log('Decoded text:', decodedText);\n },\n },\n {\n name: 'openai_test_text_to_speech',\n fn: async (runtime: IAgentRuntime) => {\n try {\n const text = 'Hello, this is a test for text-to-speech.';\n const response = await fetchTextToSpeech(runtime, text);\n if (!response) {\n throw new Error('Failed to generate speech');\n }\n logger.log('Generated speech successfully');\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(`Error in openai_test_text_to_speech: ${message}`);\n throw error;\n }\n },\n },\n ],\n },\n ],\n};\nexport default openaiPlugin;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** only globals that common to node and browsers are allowed */\n// eslint-disable-next-line node/no-unsupported-features/es-builtins\nexport const _globalThis = typeof globalThis === 'object' ? globalThis : global;\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '1.9.0';\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { VERSION } from '../version';\n\nconst re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n\n/**\n * Create a function to test an API version to see if it is compatible with the provided ownVersion.\n *\n * The returned function has the following semantics:\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param ownVersion version which should be checked against\n */\nexport function _makeCompatibilityCheck(\n ownVersion: string\n): (globalVersion: string) => boolean {\n const acceptedVersions = new Set<string>([ownVersion]);\n const rejectedVersions = new Set<string>();\n\n const myVersionMatch = ownVersion.match(re);\n if (!myVersionMatch) {\n // we cannot guarantee compatibility so we always return noop\n return () => false;\n }\n\n const ownVersionParsed = {\n major: +myVersionMatch[1],\n minor: +myVersionMatch[2],\n patch: +myVersionMatch[3],\n prerelease: myVersionMatch[4],\n };\n\n // if ownVersion has a prerelease tag, versions must match exactly\n if (ownVersionParsed.prerelease != null) {\n return function isExactmatch(globalVersion: string): boolean {\n return globalVersion === ownVersion;\n };\n }\n\n function _reject(v: string) {\n rejectedVersions.add(v);\n return false;\n }\n\n function _accept(v: string) {\n acceptedVersions.add(v);\n return true;\n }\n\n return function isCompatible(globalVersion: string): boolean {\n if (acceptedVersions.has(globalVersion)) {\n return true;\n }\n\n if (rejectedVersions.has(globalVersion)) {\n return false;\n }\n\n const globalVersionMatch = globalVersion.match(re);\n if (!globalVersionMatch) {\n // cannot parse other version\n // we cannot guarantee compatibility so we always noop\n return _reject(globalVersion);\n }\n\n const globalVersionParsed = {\n major: +globalVersionMatch[1],\n minor: +globalVersionMatch[2],\n patch: +globalVersionMatch[3],\n prerelease: globalVersionMatch[4],\n };\n\n // if globalVersion has a prerelease tag, versions must match exactly\n if (globalVersionParsed.prerelease != null) {\n return _reject(globalVersion);\n }\n\n // major versions must match\n if (ownVersionParsed.major !== globalVersionParsed.major) {\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.major === 0) {\n if (\n ownVersionParsed.minor === globalVersionParsed.minor &&\n ownVersionParsed.patch <= globalVersionParsed.patch\n ) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n }\n\n if (ownVersionParsed.minor <= globalVersionParsed.minor) {\n return _accept(globalVersion);\n }\n\n return _reject(globalVersion);\n };\n}\n\n/**\n * Test an API version to see if it is compatible with this API.\n *\n * - Exact match is always compatible\n * - Major versions must match exactly\n * - 1.x package cannot use global 2.x package\n * - 2.x package cannot use global 1.x package\n * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n * - Patch and build tag differences are not considered at this time\n *\n * @param version version of the API requesting an instance of the global API\n */\nexport const isCompatible = _makeCompatibilityCheck(VERSION);\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { MeterProvider } from '../metrics/MeterProvider';\nimport { ContextManager } from '../context/types';\nimport { DiagLogger } from '../diag/types';\nimport { _globalThis } from '../platform';\nimport { TextMapPropagator } from '../propagation/TextMapPropagator';\nimport type { TracerProvider } from '../trace/tracer_provider';\nimport { VERSION } from '../version';\nimport { isCompatible } from './semver';\n\nconst major = VERSION.split('.')[0];\nconst GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(\n `opentelemetry.js.api.${major}`\n);\n\nconst _global = _globalThis as OTelGlobal;\n\nexport function registerGlobal<Type extends keyof OTelGlobalAPI>(\n type: Type,\n instance: OTelGlobalAPI[Type],\n diag: DiagLogger,\n allowOverride = false\n): boolean {\n const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = _global[\n GLOBAL_OPENTELEMETRY_API_KEY\n ] ?? {\n version: VERSION,\n });\n\n if (!allowOverride && api[type]) {\n // already registered an API of this type\n const err = new Error(\n `@opentelemetry/api: Attempted duplicate registration of API: ${type}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n if (api.version !== VERSION) {\n // All registered APIs must be of the same version exactly\n const err = new Error(\n `@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`\n );\n diag.error(err.stack || err.message);\n return false;\n }\n\n api[type] = instance;\n diag.debug(\n `@opentelemetry/api: Registered a global for ${type} v${VERSION}.`\n );\n\n return true;\n}\n\nexport function getGlobal<Type extends keyof OTelGlobalAPI>(\n type: Type\n): OTelGlobalAPI[Type] | undefined {\n const globalVersion = _global[GLOBAL_OPENTELEMETRY_API_KEY]?.version;\n if (!globalVersion || !isCompatible(globalVersion)) {\n return;\n }\n return _global[GLOBAL_OPENTELEMETRY_API_KEY]?.[type];\n}\n\nexport function unregisterGlobal(type: keyof OTelGlobalAPI, diag: DiagLogger) {\n diag.debug(\n `@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`\n );\n const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\n if (api) {\n delete api[type];\n }\n}\n\ntype OTelGlobal = {\n [GLOBAL_OPENTELEMETRY_API_KEY]?: OTelGlobalAPI;\n};\n\ntype OTelGlobalAPI = {\n version: string;\n\n diag?: DiagLogger;\n trace?: TracerProvider;\n context?: ContextManager;\n metrics?: MeterProvider;\n propagation?: TextMapPropagator;\n};\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal } from '../internal/global-utils';\nimport { ComponentLoggerOptions, DiagLogger, DiagLogFunction } from './types';\n\n/**\n * Component Logger which is meant to be used as part of any component which\n * will add automatically additional namespace in front of the log message.\n * It will then forward all message to global diag logger\n * @example\n * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n * cLogger.debug('test');\n * // @opentelemetry/instrumentation-http test\n */\nexport class DiagComponentLogger implements DiagLogger {\n private _namespace: string;\n\n constructor(props: ComponentLoggerOptions) {\n this._namespace = props.namespace || 'DiagComponentLogger';\n }\n\n public debug(...args: any[]): void {\n return logProxy('debug', this._namespace, args);\n }\n\n public error(...args: any[]): void {\n return logProxy('error', this._namespace, args);\n }\n\n public info(...args: any[]): void {\n return logProxy('info', this._namespace, args);\n }\n\n public warn(...args: any[]): void {\n return logProxy('warn', this._namespace, args);\n }\n\n public verbose(...args: any[]): void {\n return logProxy('verbose', this._namespace, args);\n }\n}\n\nfunction logProxy(\n funcName: keyof DiagLogger,\n namespace: string,\n args: any\n): void {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) {\n return;\n }\n\n args.unshift(namespace);\n return logger[funcName](...(args as Parameters<DiagLogFunction>));\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type DiagLogFunction = (message: string, ...args: unknown[]) => void;\n\n/**\n * Defines an internal diagnostic logger interface which is used to log internal diagnostic\n * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function.\n * API provided implementations include :-\n * - a No-Op {@link createNoopDiagLogger}\n * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger}\n * - a general Console {@link DiagConsoleLogger} version.\n */\nexport interface DiagLogger {\n /** Log an error scenario that was not expected and caused the requested operation to fail. */\n error: DiagLogFunction;\n\n /**\n * Log a warning scenario to inform the developer of an issues that should be investigated.\n * The requested operation may or may not have succeeded or completed.\n */\n warn: DiagLogFunction;\n\n /**\n * Log a general informational message, this should not affect functionality.\n * This is also the default logging level so this should NOT be used for logging\n * debugging level information.\n */\n info: DiagLogFunction;\n\n /**\n * Log a general debug message that can be useful for identifying a failure.\n * Information logged at this level may include diagnostic details that would\n * help identify a failure scenario.\n * For example: Logging the order of execution of async operations.\n */\n debug: DiagLogFunction;\n\n /**\n * Log a detailed (verbose) trace level logging that can be used to identify failures\n * where debug level logging would be insufficient, this level of tracing can include\n * input and output parameters and as such may include PII information passing through\n * the API. As such it is recommended that this level of tracing should not be enabled\n * in a production environment.\n */\n verbose: DiagLogFunction;\n}\n\n/**\n * Defines the available internal logging levels for the diagnostic logger, the numeric values\n * of the levels are defined to match the original values from the initial LogLevel to avoid\n * compatibility/migration issues for any implementation that assume the numeric ordering.\n */\nexport enum DiagLogLevel {\n /** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n NONE = 0,\n\n /** Identifies an error scenario */\n ERROR = 30,\n\n /** Identifies a warning scenario */\n WARN = 50,\n\n /** General informational log message */\n INFO = 60,\n\n /** General debug log message */\n DEBUG = 70,\n\n /**\n * Detailed trace level logging should only be used for development, should only be set\n * in a development environment.\n */\n VERBOSE = 80,\n\n /** Used to set the logging level to include all logging */\n ALL = 9999,\n}\n\n/**\n * Defines options for ComponentLogger\n */\nexport interface ComponentLoggerOptions {\n namespace: string;\n}\n\nexport interface DiagLoggerOptions {\n /**\n * The {@link DiagLogLevel} used to filter logs sent to the logger.\n *\n * @defaultValue DiagLogLevel.INFO\n */\n logLevel?: DiagLogLevel;\n\n /**\n * Setting this value to `true` will suppress the warning message normally emitted when registering a logger when another logger is already registered.\n */\n suppressOverrideMessage?: boolean;\n}\n\nexport interface DiagLoggerApi {\n /**\n * Set the global DiagLogger and DiagLogLevel.\n * If a global diag logger is already set, this will override it.\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param options - A {@link DiagLoggerOptions} object. If not provided, default values will be set.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, options?: DiagLoggerOptions): boolean;\n\n /**\n *\n * @param logger - The {@link DiagLogger} instance to set as the default logger.\n * @param logLevel - The {@link DiagLogLevel} used to filter logs sent to the logger. If not provided it will default to {@link DiagLogLevel.INFO}.\n * @returns `true` if the logger was successfully registered, else `false`\n */\n setLogger(logger: DiagLogger, logLevel?: DiagLogLevel): boolean;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagLogFunction, DiagLogger, DiagLogLevel } from '../types';\n\nexport function createLogLevelDiagLogger(\n maxLevel: DiagLogLevel,\n logger: DiagLogger\n): DiagLogger {\n if (maxLevel < DiagLogLevel.NONE) {\n maxLevel = DiagLogLevel.NONE;\n } else if (maxLevel > DiagLogLevel.ALL) {\n maxLevel = DiagLogLevel.ALL;\n }\n\n // In case the logger is null or undefined\n logger = logger || {};\n\n function _filterFunc(\n funcName: keyof DiagLogger,\n theLevel: DiagLogLevel\n ): DiagLogFunction {\n const theFunc = logger[funcName];\n\n if (typeof theFunc === 'function' && maxLevel >= theLevel) {\n return theFunc.bind(logger);\n }\n return function () {};\n }\n\n return {\n error: _filterFunc('error', DiagLogLevel.ERROR),\n warn: _filterFunc('warn', DiagLogLevel.WARN),\n info: _filterFunc('info', DiagLogLevel.INFO),\n debug: _filterFunc('debug', DiagLogLevel.DEBUG),\n verbose: _filterFunc('verbose', DiagLogLevel.VERBOSE),\n };\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DiagComponentLogger } from '../diag/ComponentLogger';\nimport { createLogLevelDiagLogger } from '../diag/internal/logLevelLogger';\nimport {\n ComponentLoggerOptions,\n DiagLogFunction,\n DiagLogger,\n DiagLoggerApi,\n DiagLogLevel,\n} from '../diag/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\n\nconst API_NAME = 'diag';\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry internal\n * diagnostic API\n */\nexport class DiagAPI implements DiagLogger, DiagLoggerApi {\n private static _instance?: DiagAPI;\n\n /** Get the singleton instance of the DiagAPI API */\n public static instance(): DiagAPI {\n if (!this._instance) {\n this._instance = new DiagAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Private internal constructor\n * @private\n */\n private constructor() {\n function _logProxy(funcName: keyof DiagLogger): DiagLogFunction {\n return function (...args) {\n const logger = getGlobal('diag');\n // shortcut if logger not set\n if (!logger) return;\n return logger[funcName](...args);\n };\n }\n\n // Using self local variable for minification purposes as 'this' cannot be minified\n const self = this;\n\n // DiagAPI specific functions\n\n const setLogger: DiagLoggerApi['setLogger'] = (\n logger,\n optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }\n ) => {\n if (logger === self) {\n // There isn't much we can do here.\n // Logging to the console might break the user application.\n // Try to log to self. If a logger was previously registered it will receive the log.\n const err = new Error(\n 'Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'\n );\n self.error(err.stack ?? err.message);\n return false;\n }\n\n if (typeof optionsOrLogLevel === 'number') {\n optionsOrLogLevel = {\n logLevel: optionsOrLogLevel,\n };\n }\n\n const oldLogger = getGlobal('diag');\n const newLogger = createLogLevelDiagLogger(\n optionsOrLogLevel.logLevel ?? DiagLogLevel.INFO,\n logger\n );\n // There already is an logger registered. We'll let it know before overwriting it.\n if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n const stack = new Error().stack ?? '<failed to generate stacktrace>';\n oldLogger.warn(`Current logger will be overwritten from ${stack}`);\n newLogger.warn(\n `Current logger will overwrite one already registered from ${stack}`\n );\n }\n\n return registerGlobal('diag', newLogger, self, true);\n };\n\n self.setLogger = setLogger;\n\n self.disable = () => {\n unregisterGlobal(API_NAME, self);\n };\n\n self.createComponentLogger = (options: ComponentLoggerOptions) => {\n return new DiagComponentLogger(options);\n };\n\n self.verbose = _logProxy('verbose');\n self.debug = _logProxy('debug');\n self.info = _logProxy('info');\n self.warn = _logProxy('warn');\n self.error = _logProxy('error');\n }\n\n public setLogger!: DiagLoggerApi['setLogger'];\n /**\n *\n */\n public createComponentLogger!: (\n options: ComponentLoggerOptions\n ) => DiagLogger;\n\n // DiagLogger implementation\n public verbose!: DiagLogFunction;\n public debug!: DiagLogFunction;\n public info!: DiagLogFunction;\n public warn!: DiagLogFunction;\n public error!: DiagLogFunction;\n\n /**\n * Unregister the global logger and return to Noop\n */\n public disable!: () => void;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Context } from './types';\n\n/** Get a key to uniquely identify a context value */\nexport function createContextKey(description: string) {\n // The specification states that for the same input, multiple calls should\n // return different keys. Due to the nature of the JS dependency management\n // system, this creates problems where multiple versions of some package\n // could hold different keys for the same property.\n //\n // Therefore, we use Symbol.for which returns the same key for the same input.\n return Symbol.for(description);\n}\n\nclass BaseContext implements Context {\n private _currentContext!: Map<symbol, unknown>;\n\n /**\n * Construct a new context which inherits values from an optional parent context.\n *\n * @param parentContext a context from which to inherit values\n */\n constructor(parentContext?: Map<symbol, unknown>) {\n // for minification\n const self = this;\n\n self._currentContext = parentContext ? new Map(parentContext) : new Map();\n\n self.getValue = (key: symbol) => self._currentContext.get(key);\n\n self.setValue = (key: symbol, value: unknown): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.set(key, value);\n return context;\n };\n\n self.deleteValue = (key: symbol): Context => {\n const context = new BaseContext(self._currentContext);\n context._currentContext.delete(key);\n return context;\n };\n }\n\n /**\n * Get a value from the context.\n *\n * @param key key which identifies a context value\n */\n public getValue!: (key: symbol) => unknown;\n\n /**\n * Create a new context which inherits from this context and has\n * the given key set to the given value.\n *\n * @param key context key for which to set the value\n * @param value value to set for the given key\n */\n public setValue!: (key: symbol, value: unknown) => Context;\n\n /**\n * Return a new context which inherits from this context but does\n * not contain a value for the given key.\n *\n * @param key context key for which to clear a value\n */\n public deleteValue!: (key: symbol) => Context;\n}\n\n/** The root context is used as the default parent context when there is no active context */\nexport const ROOT_CONTEXT: Context = new BaseContext();\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ROOT_CONTEXT } from './context';\nimport * as types from './types';\n\nexport class NoopContextManager implements types.ContextManager {\n active(): types.Context {\n return ROOT_CONTEXT;\n }\n\n with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n _context: types.Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n return fn.call(thisArg, ...args);\n }\n\n bind<T>(_context: types.Context, target: T): T {\n return target;\n }\n\n enable(): this {\n return this;\n }\n\n disable(): this {\n return this;\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { NoopContextManager } from '../context/NoopContextManager';\nimport { Context, ContextManager } from '../context/types';\nimport {\n getGlobal,\n registerGlobal,\n unregisterGlobal,\n} from '../internal/global-utils';\nimport { DiagAPI } from './diag';\n\nconst API_NAME = 'context';\nconst NOOP_CONTEXT_MANAGER = new NoopContextManager();\n\n/**\n * Singleton object which represents the entry point to the OpenTelemetry Context API\n */\nexport class ContextAPI {\n private static _instance?: ContextAPI;\n\n /** Empty private constructor prevents end users from constructing a new instance of the API */\n private constructor() {}\n\n /** Get the singleton instance of the Context API */\n public static getInstance(): ContextAPI {\n if (!this._instance) {\n this._instance = new ContextAPI();\n }\n\n return this._instance;\n }\n\n /**\n * Set the current context manager.\n *\n * @returns true if the context manager was successfully registered, else false\n */\n public setGlobalContextManager(contextManager: ContextManager): boolean {\n return registerGlobal(API_NAME, contextManager, DiagAPI.instance());\n }\n\n /**\n * Get the currently active context\n */\n public active(): Context {\n return this._getContextManager().active();\n }\n\n /**\n * Execute a function with an active context\n *\n * @param context context to be active during function execution\n * @param fn function to execute in a context\n * @param thisArg optional receiver to be used for calling fn\n * @param args optional arguments forwarded to fn\n */\n public with<A extends unknown[], F extends (...args: A) => ReturnType<F>>(\n context: Context,\n fn: F,\n thisArg?: ThisParameterType<F>,\n ...args: A\n ): ReturnType<F> {\n return this._getContextManager().with(context, fn, thisArg, ...args);\n }\n\n /**\n * Bind a context to a target function or event emitter\n *\n * @param context context to bind to the event emitter or function. Defaults to the currently active context\n * @param target function or event emitter to bind\n */\n public bind<T>(context: Context, target: T): T {\n return this._getContextManager().bind(context, target);\n }\n\n private _getContextManager(): ContextManager {\n return getGlobal(API_NAME) || NOOP_CONTEXT_MANAGER;\n }\n\n /** Disable and remove the global context manager */\n public disable() {\n this._getContextManager().disable();\n unregisterGlobal(API_NAME, DiagAPI.instance());\n }\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nexport interface SpanStatus {\n /** The status code of this message. */\n code: SpanStatusCode;\n /** A developer-facing error message. */\n message?: string;\n}\n\n/**\n * An enumeration of status codes.\n */\nexport enum SpanStatusCode {\n /**\n * The default status.\n */\n UNSET = 0,\n /**\n * The operation has been validated by an Application developer or\n * Operator to have completed successfully.\n */\n OK = 1,\n /**\n * The operation contains an error.\n */\n ERROR = 2,\n}\n","/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { ContextAPI } from './api/context';\n/** Entrypoint for context API */\nexport const context = ContextAPI.getInstance();\n"],"mappings":";AAAA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AAanC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAA6B,wBAAwB;AACrD,SAAS,OAAO,gBAAgB;;;ACbzB,IAAM,cAAc,OAAO,eAAe,WAAW,aAAa;;;ACDlE,IAAM,UAAU;;;ACCvB,IAAM,KAAK;AAkBL,SAAU,wBACd,YAAkB;AAElB,MAAM,mBAAmB,oBAAI,IAAY,CAAC,UAAU,CAAC;AACrD,MAAM,mBAAmB,oBAAI,IAAG;AAEhC,MAAM,iBAAiB,WAAW,MAAM,EAAE;AAC1C,MAAI,CAAC,gBAAgB;AAEnB,WAAO,WAAA;AAAM,aAAA;IAAA;;AAGf,MAAM,mBAAmB;IACvB,OAAO,CAAC,eAAe,CAAC;IACxB,OAAO,CAAC,eAAe,CAAC;IACxB,OAAO,CAAC,eAAe,CAAC;IACxB,YAAY,eAAe,CAAC;;AAI9B,MAAI,iBAAiB,cAAc,MAAM;AACvC,WAAO,SAAS,aAAa,eAAqB;AAChD,aAAO,kBAAkB;IAC3B;;AAGF,WAAS,QAAQ,GAAS;AACxB,qBAAiB,IAAI,CAAC;AACtB,WAAO;EACT;A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pC,gBAAI;AACF,oBAAM,OAAO;AACb,oBAAM,WAAW,MAAM,kBAAkB,SAAS,IAAI;AACtD,kBAAI,CAAC,UAAU;AACb,sBAAM,IAAI,MAAM,2BAA2B;AAAA,cAC7C;AACA,qBAAO,IAAI,+BAA+B;AAAA,YAC5C,SAAS,OAAgB;AACvB,oBAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,qBAAO,MAAM,wCAAwC,OAAO,EAAE;AAC9D,oBAAM;AAAA,YACR;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AACA,IAAO,gBAAQ;","names":["isCompatible","DiagComponentLogger","logger","DiagLogLevel","logger","DiagAPI","logger","__spreadArray","__read","BaseContext","context","NoopContextManager","__spreadArray","__read","API_NAME","ContextAPI","context","__spreadArray","__read","SpanStatusCode"]}
package/package.json CHANGED
@@ -1,21 +1,30 @@
1
1
  {
2
2
  "name": "@elizaos/plugin-openai",
3
- "version": "1.0.0-beta.45",
3
+ "version": "1.0.0-beta.47",
4
4
  "type": "module",
5
- "main": "./dist/index.js",
6
- "module": "./dist/index.js",
7
- "types": "./dist/index.d.ts",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
8
  "repository": {
9
9
  "type": "git",
10
10
  "url": "https://github.com/elizaos-plugins/plugin-openai"
11
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
+ },
12
21
  "files": [
13
22
  "dist"
14
23
  ],
15
24
  "dependencies": {
16
25
  "@ai-sdk/openai": "^1.3.20",
17
26
  "@ai-sdk/ui-utils": "^1.2.8",
18
- "@elizaos/core": "^1.0.0-beta.45",
27
+ "@elizaos/core": "^1.0.0-beta.47",
19
28
  "ai": "^4.3.9",
20
29
  "js-tiktoken": "^1.0.18",
21
30
  "tsup": "8.4.0",
@@ -41,7 +50,7 @@
41
50
  }
42
51
  }
43
52
  },
44
- "gitHead": "9f9672f31e8872a2f27620f533c14ef4af62b0f2",
53
+ "gitHead": "2cfa41817cc142e362078ad82848fbd8c7802deb",
45
54
  "devDependencies": {
46
55
  "prettier": "3.5.3"
47
56
  }