@openclaw/ai 2026.11.3 → 2026.11.5-beta.2
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/README.md +11 -8
- package/dist/.source-module-urls/fe058cc430242ce2ab0dfbcbe153e240a52cf9c3072c3dc0a73e5f956b6ba49b.json +1 -0
- package/dist/anthropic-DEKgalVg.mjs +182 -0
- package/dist/{anthropic-payload-policy-C0ki72BT.d.mts → anthropic-payload-policy-CXCJ5Pmj.d.mts} +21 -4
- package/dist/{anthropic-stream-reducer-yWDb5Cct.mjs → anthropic-stream-lifecycle-DF2qVvg1.mjs} +845 -649
- package/dist/{anthropic-tool-projection-C2-d1eZ3.d.mts → anthropic-tool-projection-D5DyrL6C.d.mts} +6 -7
- package/dist/{anthropic-tool-projection-DZOKfAmL.mjs → anthropic-tool-projection-dGRfr4iT.mjs} +22 -32
- package/dist/{api-registry-gDt0faai.d.mts → api-registry-DY2MLUyg.d.mts} +2 -2
- package/dist/assistant-output-CD4kY9gu.mjs +16 -0
- package/dist/{azure-openai-responses-BvvXzZbi.mjs → azure-openai-responses-DbQV5RTx.mjs} +47 -53
- package/dist/{cloudflare-Dttf8jKq.mjs → cloudflare-BJ2_Xabx.mjs} +1 -1
- package/dist/{credential-redaction-XvsPf7Yi.d.mts → credential-redaction-DrgndwTJ.d.mts} +5 -3
- package/dist/{deferred-event-buffer-DAvyP7qA.mjs → deferred-event-buffer-tIGkTkTm.mjs} +1 -2
- package/dist/{diagnostics-v7oVEW59.mjs → diagnostics-CloVGQiK.mjs} +27 -20
- package/dist/{diagnostics-DzrF1h4J.mjs → diagnostics-o1PrVNQb.mjs} +11 -4
- package/dist/diagnostics.d.mts +6 -7
- package/dist/diagnostics.mjs +4 -4
- package/dist/{env-api-keys-Xd8dm_aV.mjs → env-api-keys-BuHc86ya.mjs} +1 -26
- package/dist/event-stream-B4ZcSvsu.d.mts +1 -0
- package/dist/{event-stream-CzpE1g_o.d.mts → event-stream-BYmtRe8-.d.mts} +1 -1
- package/dist/event-stream.d.mts +2 -2
- package/dist/event-stream.mjs +1 -2
- package/dist/expect-lbe3Hgrh.mjs +8 -0
- package/dist/{github-copilot-request-facts-F-EmvkpW.mjs → github-copilot-request-facts-BZ_EMo7X.mjs} +1 -1
- package/dist/{google-Cpi_cLKZ.mjs → google-B1g82bn4.mjs} +7 -8
- package/dist/{google-interactions-CGINbsjO.mjs → google-interactions-Ckr0Z99Z.mjs} +243 -269
- package/dist/{google-messages-DQMgG5yG.mjs → google-messages-A-9d3y5V.mjs} +52 -18
- package/dist/{google-provider-stream-BHd0cST9.mjs → google-provider-stream-CNVh4gpm.mjs} +19 -11
- package/dist/{google-shared-vtag8bj5.mjs → google-shared-WNM86ZcW.mjs} +72 -42
- package/dist/{google-vertex-eKoUnW7N.mjs → google-vertex-CXjleC6g.mjs} +3 -3
- package/dist/{google-video-slots-D8tPH8wX.mjs → google-video-slots-Bxt-OXO8.mjs} +1 -1
- package/dist/{host-CWt55nnF.mjs → host-DX7ORpeH.mjs} +46 -39
- package/dist/{host-jJOffdlW.d.mts → host-ccbwPC3A.d.mts} +17 -9
- package/dist/{host-policy-Dm7PM6AD.mjs → host-policy-jCZebuXx.mjs} +2 -2
- package/dist/index-Bczt0MnO.d.mts +17 -0
- package/dist/index.d.mts +8 -7
- package/dist/index.mjs +9 -7
- package/dist/internal/anthropic.d.mts +21 -26
- package/dist/internal/anthropic.mjs +6 -6
- package/dist/internal/google-model-family.mjs +1 -1
- package/dist/internal/google.d.mts +15 -0
- package/dist/internal/google.mjs +1 -0
- package/dist/internal/model-request-body.d.mts +37 -0
- package/dist/internal/model-request-body.mjs +106 -0
- package/dist/internal/openai-completions-compat.d.mts +1 -1
- package/dist/internal/openai-completions-compat.mjs +1 -1
- package/dist/internal/openai-responses-payload-policy.d.mts +2 -2
- package/dist/internal/openai-responses-payload-policy.mjs +2 -2
- package/dist/internal/openai.d.mts +14 -12
- package/dist/internal/openai.mjs +11 -10
- package/dist/internal/reasoning-tag-text-partitioner.d.mts +26 -0
- package/dist/{reasoning-tag-text-partitioner-CU9A4Lg8.mjs → internal/reasoning-tag-text-partitioner.mjs} +313 -111
- package/dist/internal/retry-after.d.mts +2 -2
- package/dist/internal/retry-after.mjs +96 -32
- package/dist/internal/runtime.d.mts +15 -41
- package/dist/internal/runtime.mjs +9 -10
- package/dist/internal/shared.d.mts +21 -25
- package/dist/internal/shared.mjs +9 -98
- package/dist/internal/tool-schema.d.mts +10 -10
- package/dist/internal/tool-schema.mjs +4 -4
- package/dist/{llm-request-activity-CfMuh5cC.mjs → llm-request-activity-DzaHoRAU.mjs} +2 -2
- package/dist/mistral-CjHkvsqR.mjs +3741 -0
- package/dist/{openai.LICENSE → mistral.LICENSE} +1 -1
- package/dist/{model-transport-url-BrsjjdjR.d.mts → model-transport-url-BdksnBqu.d.mts} +6 -8
- package/dist/{number-coercion-37gmNkuA.mjs → number-coercion-C7HsBgUL.mjs} +7 -2
- package/dist/observe-async-iterator-AlARO5wS.d.mts +178 -0
- package/dist/observe-async-iterator-DgmegcZR.mjs +181 -0
- package/dist/{openai-chatgpt-responses-BZa3SySh.mjs → openai-chatgpt-responses-CwS5JP7A.mjs} +61 -80
- package/dist/{openai-completions-compat-CBvb2eld.d.mts → openai-completions-compat-CJ-NsDzg.d.mts} +12 -6
- package/dist/{openai-completions-compat-bNQXF1y9.mjs → openai-completions-compat-CstlTQuF.mjs} +74 -50
- package/dist/{openai-completions-CCZ_UHCk.mjs → openai-completions-sj4S-RXQ.mjs} +5 -5
- package/dist/openai-completions-transport-BDAIA0_P.mjs +3406 -0
- package/dist/{openai-prompt-cache-DgjD-UL5.d.mts → openai-prompt-cache-BZGaIWYh.d.mts} +4 -4
- package/dist/{openai-prompt-cache-B9AvdoEo.mjs → openai-prompt-cache-CgDoFhO0.mjs} +5 -4
- package/dist/{openai-responses-compaction-replay-_sUXtcwU.d.mts → openai-responses-compaction-replay-CNHk6k53.d.mts} +4 -4
- package/dist/{openai-responses-contracts-B1nkeLL6.d.mts → openai-responses-contracts-BXMcvO7F.d.mts} +4 -10
- package/dist/{openai-responses-contracts-B5mGAbR6.mjs → openai-responses-contracts-xU-n9AJJ.mjs} +36 -37
- package/dist/{openai-responses-endpoint-CfKR6N5f.mjs → openai-responses-endpoint-DCkURKS0.mjs} +55 -8
- package/dist/openai-responses-ev_c6oTy.mjs +89 -0
- package/dist/{openai-responses-payload-policy-BzM52TTH.d.mts → openai-responses-payload-policy-DyE30gdD.d.mts} +7 -7
- package/dist/{openai-responses-request-lifecycle-CTqHc02t.mjs → openai-responses-request-lifecycle-BuOs0mwI.mjs} +12 -26
- package/dist/{openai-responses-shared-wx9v1MCn.mjs → openai-responses-shared-BmRQnUPP.mjs} +633 -1493
- package/dist/{openai-responses-terminal-usage-CpVjkqn-.d.mts → openai-responses-terminal-usage-D7IhRA6i.d.mts} +9 -3
- package/dist/{openai-tool-schema-BTEU2xmN.mjs → openai-tool-schema-CsoYgnWy.mjs} +97 -122
- package/dist/otel-Buswj0Mf.mjs +766 -0
- package/dist/{overflow-OF3PgPbw.mjs → overflow-CpApyjG2.mjs} +1 -1
- package/dist/{positive-integer-Bb4Evc7L.mjs → positive-integer-DiqE5vNi.mjs} +2 -3
- package/dist/{prompt-cache-stability-D_MeCQFI.mjs → prompt-cache-stability-w-ICeyOI.mjs} +1 -1
- package/dist/{provider-error-qtZD2inE.mjs → provider-error-DD-fo4Rz.mjs} +71 -234
- package/dist/{provider-options-DAzsyi49.d.mts → provider-options-Mo8NM5d1.d.mts} +16 -5
- package/dist/{provider-replay-context-4vxI7p4V.mjs → provider-replay-context-xyU7-CiT.mjs} +2 -2
- package/dist/provider-transcript-transform-DtaxNcC1.mjs +32 -0
- package/dist/{provider-transport-turn-state-D_GjPJHe.mjs → provider-transport-turn-state-BIS8maBK.mjs} +4 -4
- package/dist/{provider-types-CWl4VXvE.d.mts → provider-types-B1e98js5.d.mts} +3 -3
- package/dist/provider-types.d.mts +7 -6
- package/dist/providers.d.mts +2 -2
- package/dist/providers.mjs +26 -29
- package/dist/{record-coerce-CNDovvft.mjs → record-coerce-BQaoiN3r.mjs} +4 -1
- package/dist/request-headers-DO4Mqhw1.mjs +10 -0
- package/dist/{required-api-key-D088S4Cd.mjs → required-api-key-2zZTkmsi.mjs} +1 -1
- package/dist/{retry-after-BrmTv0jL.d.mts → retry-after-DnHBlFS2.d.mts} +21 -1
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/dist/{sanitize-unicode-ZqVLLEKC.d.mts → sanitize-unicode-BISmUlUv.d.mts} +2 -2
- package/dist/{simple-options-xJkqrG_E.mjs → simple-options-tLSeECry.mjs} +108 -82
- package/dist/src-BUsVkrNt.mjs +105 -0
- package/dist/{src-CyA0zJnt.mjs → src-CQ7nH2mL.mjs} +4 -7
- package/dist/stable-stringify-CchQEmeA.mjs +84 -0
- package/dist/{stream-C4YDqhFj.mjs → stream-DrtAWu7c.mjs} +2 -6
- package/dist/{stream-first-event-timeout-D_TfJHRJ.mjs → stream-first-event-timeout-B7RcufAV.mjs} +16 -13
- package/dist/{string-coerce-Cj8sqWHx.mjs → string-coerce-BCuWMIrk.mjs} +1 -1
- package/dist/string-normalization-B8TDDBX_.mjs +32 -0
- package/dist/telemetry-CvK1yQg7.mjs +582 -0
- package/dist/{tool-schema-json-projection-B1sTYwfH.mjs → tool-schema-json-projection-BQpiJlXJ.mjs} +53 -69
- package/dist/{transport-stream-shared-lhgkTOz3.mjs → transport-stream-shared-D2uFMhMc.mjs} +177 -93
- package/dist/{transport-stream-shared-8ru8eX4s.d.mts → transport-stream-shared-D3IAU4jn.d.mts} +29 -15
- package/dist/{transport-utils-DwOpuTjL.mjs → transport-utils-Da_39MYi.mjs} +23 -38
- package/dist/transports.d.mts +42 -39
- package/dist/transports.mjs +215 -296
- package/dist/{types-CVYzKrMl.d.mts → types-BVdTf0YV.d.mts} +38 -3
- package/dist/types-Cb3-5WM9.d.mts +1 -0
- package/dist/{types-BXd0kI8-.mjs → types-OVEWUaDh.mjs} +3 -1
- package/dist/types.d.mts +7 -6
- package/dist/types.mjs +7 -5
- package/dist/{validation-9FSkE8T-.mjs → validation-DGXqfvkj.mjs} +45 -27
- package/dist/{validation-BQ5u20Ru.d.mts → validation-QmyD0E5A.d.mts} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -2
- package/package.json +40 -6
- package/dist/anthropic-lueA8LUg.mjs +0 -221
- package/dist/assistant-output-BnQm3fov.mjs +0 -47
- package/dist/event-stream-CDpFza-M.d.mts +0 -1
- package/dist/index-DSprYWaz.d.mts +0 -185
- package/dist/mistral-CQ7aoWg2.mjs +0 -512
- package/dist/model-request-body-BD5vy4rP.d.mts +0 -17
- package/dist/openai-CiRi-nVE.mjs +0 -20077
- package/dist/openai-completions-transport-DFvSBbUT.mjs +0 -10881
- package/dist/openai-responses-DQsZKUoI.mjs +0 -87
- package/dist/rolldown-runtime-B4iAMlE-.mjs +0 -35
- package/dist/types-CBJthzJX.d.mts +0 -1
- package/dist/ws.LICENSE +0 -20
|
@@ -0,0 +1,766 @@
|
|
|
1
|
+
import { a as registerTracerProvider, i as getRegisteredTracerProvider, n as completionChunkFromJSON, r as UsageInfo$outboundSchema } from "./mistral-CjHkvsqR.mjs";
|
|
2
|
+
import { SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
|
|
3
|
+
import { ATTR_ERROR_TYPE, ATTR_GEN_AI_AGENT_DESCRIPTION, ATTR_GEN_AI_AGENT_ID, ATTR_GEN_AI_AGENT_NAME, ATTR_GEN_AI_CONVERSATION_ID, ATTR_GEN_AI_INPUT_MESSAGES, ATTR_GEN_AI_OPERATION_NAME, ATTR_GEN_AI_OUTPUT_MESSAGES, ATTR_GEN_AI_PROVIDER_NAME, ATTR_GEN_AI_REQUEST_CHOICE_COUNT, ATTR_GEN_AI_REQUEST_ENCODING_FORMATS, ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY, ATTR_GEN_AI_REQUEST_MAX_TOKENS, ATTR_GEN_AI_REQUEST_MODEL, ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY, ATTR_GEN_AI_REQUEST_SEED, ATTR_GEN_AI_REQUEST_STOP_SEQUENCES, ATTR_GEN_AI_REQUEST_TEMPERATURE, ATTR_GEN_AI_REQUEST_TOP_K, ATTR_GEN_AI_REQUEST_TOP_P, ATTR_GEN_AI_RESPONSE_FINISH_REASONS, ATTR_GEN_AI_RESPONSE_ID, ATTR_GEN_AI_RESPONSE_MODEL, ATTR_GEN_AI_SYSTEM_INSTRUCTIONS, ATTR_GEN_AI_TOOL_CALL_ARGUMENTS, ATTR_GEN_AI_TOOL_CALL_ID, ATTR_GEN_AI_TOOL_CALL_RESULT, ATTR_GEN_AI_TOOL_DEFINITIONS, ATTR_GEN_AI_TOOL_NAME, ATTR_GEN_AI_TOOL_TYPE, ATTR_GEN_AI_USAGE_INPUT_TOKENS, ATTR_GEN_AI_USAGE_OUTPUT_TOKENS, ATTR_HTTP_REQUEST_METHOD, ATTR_HTTP_RESPONSE_STATUS_CODE, ATTR_SERVER_ADDRESS, ATTR_SERVER_PORT, ATTR_URL_FULL, GEN_AI_OPERATION_NAME_VALUE_CHAT, GEN_AI_OPERATION_NAME_VALUE_CREATE_AGENT, GEN_AI_OPERATION_NAME_VALUE_EMBEDDINGS, GEN_AI_OPERATION_NAME_VALUE_EXECUTE_TOOL, GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT, GEN_AI_OPERATION_NAME_VALUE_INVOKE_AGENT, GEN_AI_OPERATION_NAME_VALUE_TEXT_COMPLETION, GEN_AI_PROVIDER_NAME_VALUE_MISTRAL_AI } from "@opentelemetry/semantic-conventions/incubating";
|
|
4
|
+
//#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/extra/observability/formatting.js
|
|
5
|
+
/**
|
|
6
|
+
* Formatting helpers for converting Mistral API payloads to OTEL GenAI convention formats.
|
|
7
|
+
*
|
|
8
|
+
* These are pure functions with no OTEL dependencies - they transform objects to objects
|
|
9
|
+
* matching the GenAI semantic convention schemas for input/output messages and tool definitions.
|
|
10
|
+
* The caller is responsible for the final JSON serialization (single JSON.stringify on the whole
|
|
11
|
+
* collection) before setting span attributes.
|
|
12
|
+
*
|
|
13
|
+
* Schemas:
|
|
14
|
+
* - Input messages: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-input-messages.json
|
|
15
|
+
* - Output messages: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-output-messages.json
|
|
16
|
+
* - Tool definitions: https://github.com/Cirilla-zmh/semantic-conventions/blob/cc4d07e7e56b80e9aa5904a3d524c134699da37f/docs/gen-ai/gen-ai-tool-definitions.json
|
|
17
|
+
*/
|
|
18
|
+
/**
|
|
19
|
+
* Convert Mistral message content to OTEL parts array.
|
|
20
|
+
*
|
|
21
|
+
* Mistral content is either a string or an array of content chunks.
|
|
22
|
+
*/
|
|
23
|
+
function contentToParts(content) {
|
|
24
|
+
if (content == null) return [];
|
|
25
|
+
if (typeof content === "string") return [{
|
|
26
|
+
type: "text",
|
|
27
|
+
content
|
|
28
|
+
}];
|
|
29
|
+
if (!Array.isArray(content)) return [];
|
|
30
|
+
const parts = [];
|
|
31
|
+
for (const chunk of content) if (typeof chunk === "string") parts.push({
|
|
32
|
+
type: "text",
|
|
33
|
+
content: chunk
|
|
34
|
+
});
|
|
35
|
+
else if (typeof chunk === "object" && chunk !== null) {
|
|
36
|
+
const c = chunk;
|
|
37
|
+
const chunkType = c["type"] || "";
|
|
38
|
+
if (chunkType === "text") parts.push({
|
|
39
|
+
type: "text",
|
|
40
|
+
content: c["text"] || ""
|
|
41
|
+
});
|
|
42
|
+
else if (chunkType === "thinking") {
|
|
43
|
+
const thinking = c["thinking"];
|
|
44
|
+
let contentStr;
|
|
45
|
+
if (Array.isArray(thinking)) contentStr = thinking.filter((sub) => typeof sub === "object" && sub !== null && sub["type"] === "text").map((sub) => sub["text"] || "").join("\n");
|
|
46
|
+
else contentStr = String(thinking || "");
|
|
47
|
+
parts.push({
|
|
48
|
+
type: "reasoning",
|
|
49
|
+
content: contentStr
|
|
50
|
+
});
|
|
51
|
+
} else if (chunkType === "image_url") {
|
|
52
|
+
const url = c["image_url"];
|
|
53
|
+
const uri = typeof url === "object" && url !== null ? url["url"] || "" : String(url || "");
|
|
54
|
+
parts.push({
|
|
55
|
+
type: "uri",
|
|
56
|
+
modality: "image",
|
|
57
|
+
uri
|
|
58
|
+
});
|
|
59
|
+
} else parts.push({ type: chunkType });
|
|
60
|
+
}
|
|
61
|
+
return parts;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Convert Mistral tool_calls to OTEL ToolCallRequestPart entries.
|
|
65
|
+
*/
|
|
66
|
+
function toolCallsToParts(toolCalls) {
|
|
67
|
+
if (!toolCalls || !Array.isArray(toolCalls)) return [];
|
|
68
|
+
const parts = [];
|
|
69
|
+
for (const tc of toolCalls) {
|
|
70
|
+
if (typeof tc !== "object" || tc === null) continue;
|
|
71
|
+
const tcObj = tc;
|
|
72
|
+
const func = tcObj["function"] || {};
|
|
73
|
+
const part = {
|
|
74
|
+
type: "tool_call",
|
|
75
|
+
name: func["name"] || ""
|
|
76
|
+
};
|
|
77
|
+
const tcId = tcObj["id"];
|
|
78
|
+
if (tcId != null) part["id"] = tcId;
|
|
79
|
+
const args = func["arguments"];
|
|
80
|
+
if (args != null) part["arguments"] = args;
|
|
81
|
+
parts.push(part);
|
|
82
|
+
}
|
|
83
|
+
return parts;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Format a single input message per the OTEL GenAI convention.
|
|
87
|
+
*
|
|
88
|
+
* Schema: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-input-messages.json
|
|
89
|
+
* ChatMessage: {role (required), parts (required), name?}
|
|
90
|
+
*
|
|
91
|
+
* Conversation entry objects (e.g. function.result) don't carry a "role"
|
|
92
|
+
* field - they are detected via their "type" and mapped to the closest OTEL role.
|
|
93
|
+
*/
|
|
94
|
+
function formatInputMessage(message) {
|
|
95
|
+
if (message["type"] === "function.result") {
|
|
96
|
+
const part = {
|
|
97
|
+
type: "tool_call_response",
|
|
98
|
+
response: message["result"]
|
|
99
|
+
};
|
|
100
|
+
const toolCallId = message["tool_call_id"];
|
|
101
|
+
if (toolCallId != null) part["id"] = toolCallId;
|
|
102
|
+
return {
|
|
103
|
+
role: "tool",
|
|
104
|
+
parts: [part]
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
const role = message["role"] || "unknown";
|
|
108
|
+
const parts = [];
|
|
109
|
+
if (role === "tool") {
|
|
110
|
+
const toolPart = {
|
|
111
|
+
type: "tool_call_response",
|
|
112
|
+
response: message["content"]
|
|
113
|
+
};
|
|
114
|
+
const toolCallId = message["tool_call_id"];
|
|
115
|
+
if (toolCallId != null) toolPart["id"] = toolCallId;
|
|
116
|
+
parts.push(toolPart);
|
|
117
|
+
} else {
|
|
118
|
+
parts.push(...contentToParts(message["content"]));
|
|
119
|
+
parts.push(...toolCallsToParts(message["tool_calls"]));
|
|
120
|
+
}
|
|
121
|
+
return {
|
|
122
|
+
role,
|
|
123
|
+
parts
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Format a single output choice/message per the OTEL GenAI convention.
|
|
128
|
+
*
|
|
129
|
+
* Schema: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/gen-ai-output-messages.json
|
|
130
|
+
* OutputMessage: {role (required), parts (required), finish_reason (required), name?}
|
|
131
|
+
*/
|
|
132
|
+
function formatOutputMessage(choice) {
|
|
133
|
+
const message = choice["message"] || {};
|
|
134
|
+
const parts = [];
|
|
135
|
+
parts.push(...contentToParts(message["content"]));
|
|
136
|
+
parts.push(...toolCallsToParts(message["tool_calls"]));
|
|
137
|
+
return {
|
|
138
|
+
role: message["role"] || "assistant",
|
|
139
|
+
parts,
|
|
140
|
+
finish_reason: choice["finish_reason"] || ""
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Flatten a Mistral tool definition to the OTEL GenAI convention schema.
|
|
145
|
+
*
|
|
146
|
+
* Mistral format: {"type": "function", "function": {"name": ..., "description": ..., "parameters": ...}}
|
|
147
|
+
* OTEL format: {"type": "function", "name": ..., "description": ..., "parameters": ...}
|
|
148
|
+
*
|
|
149
|
+
* Schema, still under review: https://github.com/open-telemetry/semantic-conventions
|
|
150
|
+
*/
|
|
151
|
+
function formatToolDefinition(tool) {
|
|
152
|
+
const type = tool["type"] || "function";
|
|
153
|
+
const func = tool["function"];
|
|
154
|
+
if (!func) return null;
|
|
155
|
+
const name = func["name"];
|
|
156
|
+
if (!name) return null;
|
|
157
|
+
const formatted = {
|
|
158
|
+
type,
|
|
159
|
+
name
|
|
160
|
+
};
|
|
161
|
+
const description = func["description"];
|
|
162
|
+
if (description != null) formatted["description"] = description;
|
|
163
|
+
const parameters = func["parameters"];
|
|
164
|
+
if (parameters != null) formatted["parameters"] = parameters;
|
|
165
|
+
return formatted;
|
|
166
|
+
}
|
|
167
|
+
//#endregion
|
|
168
|
+
//#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/extra/observability/streaming.js
|
|
169
|
+
/**
|
|
170
|
+
* Streaming response helpers for OTEL tracing.
|
|
171
|
+
*
|
|
172
|
+
* Pure functions that parse SSE byte streams and accumulate CompletionChunk
|
|
173
|
+
* deltas into a ChatCompletionResponse-shaped dict suitable for span enrichment.
|
|
174
|
+
*
|
|
175
|
+
* NOTE: The SSE bytes are re-parsed here even though EventStream already
|
|
176
|
+
* parsed them during iteration.
|
|
177
|
+
* TracedResponse sits below EventStream and can only accumulate raw bytes; it
|
|
178
|
+
* has no access to the decoded events. Hooking into EventStream could eliminate
|
|
179
|
+
* this double-parse, but EventStream is Speakeasy-generated code.
|
|
180
|
+
*/
|
|
181
|
+
function normalizeCompletionChunkPayload(payload) {
|
|
182
|
+
const parsed = JSON.parse(payload);
|
|
183
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return payload;
|
|
184
|
+
const chunk = parsed;
|
|
185
|
+
for (const field of [
|
|
186
|
+
"object",
|
|
187
|
+
"created",
|
|
188
|
+
"usage"
|
|
189
|
+
]) if (chunk[field] === null) delete chunk[field];
|
|
190
|
+
const choices = chunk["choices"];
|
|
191
|
+
if (Array.isArray(choices)) {
|
|
192
|
+
for (const choice of choices) if (typeof choice === "object" && choice !== null && !Array.isArray(choice)) {
|
|
193
|
+
const choiceObj = choice;
|
|
194
|
+
if (!("finish_reason" in choiceObj)) choiceObj["finish_reason"] = null;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return JSON.stringify(chunk);
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Parse raw SSE text into a list of typed CompletionChunk models.
|
|
201
|
+
*
|
|
202
|
+
* Only CompletionChunk is handled. If new SSE-streamed response types
|
|
203
|
+
* are added, parsing and typing here will need updating.
|
|
204
|
+
*/
|
|
205
|
+
function parseSseChunks(rawSseText) {
|
|
206
|
+
const chunks = [];
|
|
207
|
+
const lines = rawSseText.split("\n");
|
|
208
|
+
for (const line of lines) {
|
|
209
|
+
const trimmed = line.trim();
|
|
210
|
+
if (!trimmed.startsWith("data: ")) continue;
|
|
211
|
+
const payload = trimmed.slice(6);
|
|
212
|
+
if (payload === "[DONE]") continue;
|
|
213
|
+
try {
|
|
214
|
+
const result = completionChunkFromJSON(normalizeCompletionChunkPayload(payload));
|
|
215
|
+
if (result.ok) chunks.push(result.value);
|
|
216
|
+
} catch {
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return chunks;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Accumulate streaming CompletionChunk deltas into a ChatCompletionResponse-shaped dict.
|
|
224
|
+
*/
|
|
225
|
+
function accumulateChunksToResponseDict(chunks) {
|
|
226
|
+
let responseId;
|
|
227
|
+
let model;
|
|
228
|
+
let usage;
|
|
229
|
+
const choices = /* @__PURE__ */ new Map();
|
|
230
|
+
for (const chunk of chunks) {
|
|
231
|
+
responseId = responseId || chunk.id;
|
|
232
|
+
model = model || chunk.model;
|
|
233
|
+
usage = usage || chunk.usage;
|
|
234
|
+
for (const choice of chunk.choices) {
|
|
235
|
+
let accumulated = choices.get(choice.index);
|
|
236
|
+
if (!accumulated) {
|
|
237
|
+
accumulated = {
|
|
238
|
+
message: {
|
|
239
|
+
role: "assistant",
|
|
240
|
+
content: ""
|
|
241
|
+
},
|
|
242
|
+
finish_reason: ""
|
|
243
|
+
};
|
|
244
|
+
choices.set(choice.index, accumulated);
|
|
245
|
+
}
|
|
246
|
+
const msg = accumulated.message;
|
|
247
|
+
const delta = choice.delta;
|
|
248
|
+
if (typeof delta.role === "string") msg.role = delta.role;
|
|
249
|
+
msg.content += extractOutputText(delta.content);
|
|
250
|
+
if (typeof choice.finishReason === "string") accumulated.finish_reason = choice.finishReason;
|
|
251
|
+
if (Array.isArray(delta.toolCalls)) {
|
|
252
|
+
if (!msg.tool_calls) msg.tool_calls = [];
|
|
253
|
+
const toolCalls = msg.tool_calls;
|
|
254
|
+
for (const tc of delta.toolCalls) {
|
|
255
|
+
const tcIdx = tc.index != null ? tc.index : toolCalls.length;
|
|
256
|
+
while (toolCalls.length <= tcIdx) toolCalls.push({
|
|
257
|
+
id: null,
|
|
258
|
+
function: {
|
|
259
|
+
name: "",
|
|
260
|
+
arguments: ""
|
|
261
|
+
}
|
|
262
|
+
});
|
|
263
|
+
const existing = toolCalls[tcIdx];
|
|
264
|
+
if (tc.id != null && tc.id !== "null") existing.id = tc.id;
|
|
265
|
+
if (tc.function.name) existing.function.name += tc.function.name;
|
|
266
|
+
if (typeof tc.function.arguments === "string" && tc.function.arguments) existing.function.arguments += tc.function.arguments;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const sortedIndices = Array.from(choices.keys()).sort((a, b) => a - b);
|
|
272
|
+
const result = {
|
|
273
|
+
id: responseId,
|
|
274
|
+
model,
|
|
275
|
+
choices: sortedIndices.map((idx) => choices.get(idx))
|
|
276
|
+
};
|
|
277
|
+
if (usage != null) result["usage"] = UsageInfo$outboundSchema.parse(usage);
|
|
278
|
+
return result;
|
|
279
|
+
}
|
|
280
|
+
function extractOutputText(content) {
|
|
281
|
+
if (typeof content === "string") return content;
|
|
282
|
+
if (!Array.isArray(content)) return "";
|
|
283
|
+
return content.filter((block) => block.type === "text").map((block) => block.text).join("");
|
|
284
|
+
}
|
|
285
|
+
//#endregion
|
|
286
|
+
//#region node_modules/.pnpm/@mistralai+mistralai@2.7.0_@opentelemetry+api@1.9.1_@opentelemetry+exporter-trace-otlp-_ef8dce160c897b96339bfd78f5c612fa/node_modules/@mistralai/mistralai/esm/extra/observability/otel.js
|
|
287
|
+
/**
|
|
288
|
+
* OTEL conventions for gen AI may be found at:
|
|
289
|
+
*
|
|
290
|
+
* https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/
|
|
291
|
+
* https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-agent-spans/
|
|
292
|
+
*/
|
|
293
|
+
const semConvAttributes = {
|
|
294
|
+
ATTR_ERROR_TYPE,
|
|
295
|
+
ATTR_GEN_AI_AGENT_DESCRIPTION,
|
|
296
|
+
ATTR_GEN_AI_AGENT_ID,
|
|
297
|
+
ATTR_GEN_AI_AGENT_NAME,
|
|
298
|
+
ATTR_GEN_AI_CONVERSATION_ID,
|
|
299
|
+
ATTR_GEN_AI_INPUT_MESSAGES,
|
|
300
|
+
ATTR_GEN_AI_OPERATION_NAME,
|
|
301
|
+
ATTR_GEN_AI_OUTPUT_MESSAGES,
|
|
302
|
+
ATTR_GEN_AI_PROVIDER_NAME,
|
|
303
|
+
ATTR_GEN_AI_REQUEST_CHOICE_COUNT,
|
|
304
|
+
ATTR_GEN_AI_REQUEST_ENCODING_FORMATS,
|
|
305
|
+
ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY,
|
|
306
|
+
ATTR_GEN_AI_REQUEST_MAX_TOKENS,
|
|
307
|
+
ATTR_GEN_AI_REQUEST_MODEL,
|
|
308
|
+
ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY,
|
|
309
|
+
ATTR_GEN_AI_REQUEST_SEED,
|
|
310
|
+
ATTR_GEN_AI_REQUEST_STOP_SEQUENCES,
|
|
311
|
+
ATTR_GEN_AI_REQUEST_TEMPERATURE,
|
|
312
|
+
ATTR_GEN_AI_REQUEST_TOP_K,
|
|
313
|
+
ATTR_GEN_AI_REQUEST_TOP_P,
|
|
314
|
+
ATTR_GEN_AI_RESPONSE_FINISH_REASONS,
|
|
315
|
+
ATTR_GEN_AI_RESPONSE_ID,
|
|
316
|
+
ATTR_GEN_AI_RESPONSE_MODEL,
|
|
317
|
+
ATTR_GEN_AI_SYSTEM_INSTRUCTIONS,
|
|
318
|
+
ATTR_GEN_AI_TOOL_CALL_ARGUMENTS,
|
|
319
|
+
ATTR_GEN_AI_TOOL_CALL_ID,
|
|
320
|
+
ATTR_GEN_AI_TOOL_CALL_RESULT,
|
|
321
|
+
ATTR_GEN_AI_TOOL_DEFINITIONS,
|
|
322
|
+
ATTR_GEN_AI_TOOL_NAME,
|
|
323
|
+
ATTR_GEN_AI_TOOL_TYPE,
|
|
324
|
+
ATTR_GEN_AI_USAGE_INPUT_TOKENS,
|
|
325
|
+
ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,
|
|
326
|
+
ATTR_HTTP_REQUEST_METHOD,
|
|
327
|
+
ATTR_HTTP_RESPONSE_STATUS_CODE,
|
|
328
|
+
ATTR_SERVER_ADDRESS,
|
|
329
|
+
ATTR_SERVER_PORT,
|
|
330
|
+
ATTR_URL_FULL,
|
|
331
|
+
GEN_AI_OPERATION_NAME_VALUE_CHAT,
|
|
332
|
+
GEN_AI_OPERATION_NAME_VALUE_CREATE_AGENT,
|
|
333
|
+
GEN_AI_OPERATION_NAME_VALUE_EMBEDDINGS,
|
|
334
|
+
GEN_AI_OPERATION_NAME_VALUE_EXECUTE_TOOL,
|
|
335
|
+
GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT,
|
|
336
|
+
GEN_AI_OPERATION_NAME_VALUE_INVOKE_AGENT,
|
|
337
|
+
GEN_AI_OPERATION_NAME_VALUE_TEXT_COMPLETION,
|
|
338
|
+
GEN_AI_PROVIDER_NAME_VALUE_MISTRAL_AI
|
|
339
|
+
};
|
|
340
|
+
const OTEL_SERVICE_NAME = "mistralai_sdk";
|
|
341
|
+
const MISTRAL_SDK_OTEL_TRACER_NAME = `${OTEL_SERVICE_NAME}_tracer`;
|
|
342
|
+
const MISTRAL_AGENT_TRACE_PUBLIC_ATTRIBUTE = "agent.trace.public";
|
|
343
|
+
const getDebugTracing = () => {
|
|
344
|
+
try {
|
|
345
|
+
if (typeof globalThis !== "undefined" && "process" in globalThis) return globalThis.process?.env?.["MISTRAL_SDK_DEBUG_TRACING"]?.toLowerCase() === "true";
|
|
346
|
+
} catch {}
|
|
347
|
+
return false;
|
|
348
|
+
};
|
|
349
|
+
const MISTRAL_SDK_DEBUG_TRACING = getDebugTracing();
|
|
350
|
+
const DEBUG_HINT = "To see detailed tracing logs, set MISTRAL_SDK_DEBUG_TRACING=true.";
|
|
351
|
+
const MistralAIAttributes = {
|
|
352
|
+
MISTRAL_AI_OCR_USAGE_PAGES_PROCESSED: "mistral_ai.ocr.usage.pages_processed",
|
|
353
|
+
MISTRAL_AI_OCR_USAGE_DOC_SIZE_BYTES: "mistral_ai.ocr.usage.doc_size_bytes",
|
|
354
|
+
MISTRAL_AI_ERROR_CODE: "mistral_ai.error.code"
|
|
355
|
+
};
|
|
356
|
+
const TracingErrors = {
|
|
357
|
+
FAILED_TO_CREATE_SPAN_FOR_REQUEST: "Failed to create span for request.",
|
|
358
|
+
FAILED_TO_ENRICH_SPAN_WITH_RESPONSE: "Failed to enrich span with response.",
|
|
359
|
+
FAILED_TO_HANDLE_ERROR_IN_SPAN: "Failed to handle error in span.",
|
|
360
|
+
FAILED_TO_END_SPAN: "Failed to end span."
|
|
361
|
+
};
|
|
362
|
+
function parseTimeToMillis(ts) {
|
|
363
|
+
return new Date(ts).getTime();
|
|
364
|
+
}
|
|
365
|
+
function inferGenAiOperationName(operationId) {
|
|
366
|
+
if (operationId.includes("chat_completion") || operationId === "stream_chat") return GEN_AI_OPERATION_NAME_VALUE_CHAT;
|
|
367
|
+
if ((operationId.includes("agents_create") || operationId.includes("agents_update")) && !operationId.includes("alias")) return GEN_AI_OPERATION_NAME_VALUE_CREATE_AGENT;
|
|
368
|
+
if (operationId.includes("agents_completion") || operationId === "stream_agents") return GEN_AI_OPERATION_NAME_VALUE_INVOKE_AGENT;
|
|
369
|
+
if (operationId.includes("conversations") && (operationId.includes("start") || operationId.includes("append") || operationId.includes("restart"))) return GEN_AI_OPERATION_NAME_VALUE_INVOKE_AGENT;
|
|
370
|
+
if (operationId.includes("fim")) return GEN_AI_OPERATION_NAME_VALUE_TEXT_COMPLETION;
|
|
371
|
+
if (operationId.includes("embeddings")) return GEN_AI_OPERATION_NAME_VALUE_EMBEDDINGS;
|
|
372
|
+
if (operationId.includes("ocr_post")) return GEN_AI_OPERATION_NAME_VALUE_GENERATE_CONTENT;
|
|
373
|
+
return null;
|
|
374
|
+
}
|
|
375
|
+
function isKnownGenAiOperation(operationId) {
|
|
376
|
+
return inferGenAiOperationName(operationId) !== null;
|
|
377
|
+
}
|
|
378
|
+
function isJsonContentType(contentType) {
|
|
379
|
+
const mediaType = contentType?.split(";")[0]?.trim().toLowerCase();
|
|
380
|
+
return mediaType === "application/json" || mediaType === "text/json" || mediaType?.endsWith("+json") === true;
|
|
381
|
+
}
|
|
382
|
+
function buildGenaiSpanName(genAiOp, body) {
|
|
383
|
+
if (genAiOp === GEN_AI_OPERATION_NAME_VALUE_CREATE_AGENT || genAiOp === GEN_AI_OPERATION_NAME_VALUE_INVOKE_AGENT) {
|
|
384
|
+
const agentName = body["name"];
|
|
385
|
+
return agentName ? `${genAiOp} ${agentName}` : genAiOp;
|
|
386
|
+
}
|
|
387
|
+
if (genAiOp === GEN_AI_OPERATION_NAME_VALUE_EXECUTE_TOOL) {
|
|
388
|
+
const toolName = body["name"];
|
|
389
|
+
return toolName ? `${genAiOp} ${toolName}` : genAiOp;
|
|
390
|
+
}
|
|
391
|
+
const model = body["model"];
|
|
392
|
+
return model ? `${genAiOp} ${model}` : genAiOp;
|
|
393
|
+
}
|
|
394
|
+
function setAvailableAttributes(span, attributes) {
|
|
395
|
+
for (const [key, value] of Object.entries(attributes)) if (value != null && value !== "") span.setAttribute(key, value);
|
|
396
|
+
}
|
|
397
|
+
function setMistralAgentTraceMarker(span) {
|
|
398
|
+
span.setAttribute(MISTRAL_AGENT_TRACE_PUBLIC_ATTRIBUTE, "");
|
|
399
|
+
}
|
|
400
|
+
function setHttpAttributes(span, url, method, host) {
|
|
401
|
+
let port = url.port ? parseInt(url.port, 10) : -1;
|
|
402
|
+
if (port === -1) {
|
|
403
|
+
if (url.protocol === "https:") port = 443;
|
|
404
|
+
else if (url.protocol === "http:") port = 80;
|
|
405
|
+
}
|
|
406
|
+
span.setAttributes({
|
|
407
|
+
[ATTR_HTTP_REQUEST_METHOD]: method,
|
|
408
|
+
[ATTR_URL_FULL]: url.toString(),
|
|
409
|
+
[ATTR_SERVER_ADDRESS]: host,
|
|
410
|
+
[ATTR_SERVER_PORT]: port
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
function enrichRequestGenaiAttrs(span, genAiOp, requestBody) {
|
|
414
|
+
span.updateName(buildGenaiSpanName(genAiOp, requestBody));
|
|
415
|
+
const attributes = {
|
|
416
|
+
[ATTR_GEN_AI_REQUEST_CHOICE_COUNT]: requestBody["n"],
|
|
417
|
+
[ATTR_GEN_AI_REQUEST_ENCODING_FORMATS]: requestBody["encoding_formats"],
|
|
418
|
+
[ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY]: requestBody["frequency_penalty"],
|
|
419
|
+
[ATTR_GEN_AI_REQUEST_MAX_TOKENS]: requestBody["max_tokens"],
|
|
420
|
+
[ATTR_GEN_AI_REQUEST_MODEL]: requestBody["model"],
|
|
421
|
+
[ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY]: requestBody["presence_penalty"],
|
|
422
|
+
[ATTR_GEN_AI_REQUEST_SEED]: requestBody["random_seed"],
|
|
423
|
+
[ATTR_GEN_AI_REQUEST_STOP_SEQUENCES]: requestBody["stop"],
|
|
424
|
+
[ATTR_GEN_AI_REQUEST_TEMPERATURE]: requestBody["temperature"],
|
|
425
|
+
[ATTR_GEN_AI_REQUEST_TOP_P]: requestBody["top_p"],
|
|
426
|
+
[ATTR_GEN_AI_REQUEST_TOP_K]: requestBody["top_k"]
|
|
427
|
+
};
|
|
428
|
+
const inputMessages = requestBody["messages"] || requestBody["inputs"];
|
|
429
|
+
if (typeof inputMessages === "string") attributes[ATTR_GEN_AI_INPUT_MESSAGES] = JSON.stringify([formatInputMessage({
|
|
430
|
+
role: "user",
|
|
431
|
+
content: inputMessages
|
|
432
|
+
})]);
|
|
433
|
+
else if (Array.isArray(inputMessages)) attributes[ATTR_GEN_AI_INPUT_MESSAGES] = JSON.stringify(inputMessages.map((msg) => formatInputMessage(msg)));
|
|
434
|
+
const tools = requestBody["tools"];
|
|
435
|
+
if (tools) {
|
|
436
|
+
const formattedTools = tools.map((tool) => formatToolDefinition(tool)).filter((t) => t !== null);
|
|
437
|
+
if (formattedTools.length > 0) attributes[ATTR_GEN_AI_TOOL_DEFINITIONS] = JSON.stringify(formattedTools);
|
|
438
|
+
}
|
|
439
|
+
setAvailableAttributes(span, attributes);
|
|
440
|
+
}
|
|
441
|
+
function enrichSpanFromRequest(span, operationId, url, method, host, body) {
|
|
442
|
+
setHttpAttributes(span, url, method, host);
|
|
443
|
+
const genAiOp = inferGenAiOperationName(operationId);
|
|
444
|
+
if (genAiOp === null) return span;
|
|
445
|
+
span.setAttributes({
|
|
446
|
+
[ATTR_GEN_AI_OPERATION_NAME]: genAiOp,
|
|
447
|
+
[ATTR_GEN_AI_PROVIDER_NAME]: GEN_AI_PROVIDER_NAME_VALUE_MISTRAL_AI
|
|
448
|
+
});
|
|
449
|
+
if (body) try {
|
|
450
|
+
enrichRequestGenaiAttrs(span, genAiOp, JSON.parse(body));
|
|
451
|
+
} catch {}
|
|
452
|
+
return span;
|
|
453
|
+
}
|
|
454
|
+
function enrichResponseGenaiAttrs(span, genAiOp, responseData) {
|
|
455
|
+
const attributes = {};
|
|
456
|
+
if (genAiOp !== GEN_AI_OPERATION_NAME_VALUE_CREATE_AGENT) attributes[ATTR_GEN_AI_RESPONSE_ID] = responseData["id"];
|
|
457
|
+
attributes[ATTR_GEN_AI_RESPONSE_MODEL] = responseData["model"];
|
|
458
|
+
const choices = responseData["choices"] || [];
|
|
459
|
+
const finishReasons = choices.map((c) => c["finish_reason"]).filter((r) => !!r);
|
|
460
|
+
if (finishReasons.length > 0) attributes[ATTR_GEN_AI_RESPONSE_FINISH_REASONS] = finishReasons;
|
|
461
|
+
if (choices.length > 0) attributes[ATTR_GEN_AI_OUTPUT_MESSAGES] = JSON.stringify(choices.map((choice) => formatOutputMessage(choice)));
|
|
462
|
+
const usage = responseData["usage"];
|
|
463
|
+
if (usage) {
|
|
464
|
+
attributes[ATTR_GEN_AI_USAGE_INPUT_TOKENS] = usage["prompt_tokens"] || 0;
|
|
465
|
+
attributes[ATTR_GEN_AI_USAGE_OUTPUT_TOKENS] = usage["completion_tokens"] || 0;
|
|
466
|
+
}
|
|
467
|
+
setAvailableAttributes(span, attributes);
|
|
468
|
+
}
|
|
469
|
+
function enrichCreateAgent(span, responseData) {
|
|
470
|
+
setAvailableAttributes(span, {
|
|
471
|
+
[ATTR_GEN_AI_AGENT_DESCRIPTION]: responseData["description"],
|
|
472
|
+
[ATTR_GEN_AI_AGENT_ID]: responseData["id"],
|
|
473
|
+
[ATTR_GEN_AI_AGENT_NAME]: responseData["name"],
|
|
474
|
+
"gen_ai.agent.version": String(responseData["version"]),
|
|
475
|
+
[ATTR_GEN_AI_REQUEST_MODEL]: responseData["model"],
|
|
476
|
+
[ATTR_GEN_AI_SYSTEM_INSTRUCTIONS]: responseData["instructions"]
|
|
477
|
+
});
|
|
478
|
+
}
|
|
479
|
+
function stringifyToolAttribute(value) {
|
|
480
|
+
if (typeof value === "string") return value;
|
|
481
|
+
if (value) return JSON.stringify(value);
|
|
482
|
+
return null;
|
|
483
|
+
}
|
|
484
|
+
function createToolExecutionChildSpan(tracer, parentContext, output) {
|
|
485
|
+
const startMs = parseTimeToMillis(output["created_at"]);
|
|
486
|
+
const endMs = parseTimeToMillis(output["completed_at"]);
|
|
487
|
+
const opName = GEN_AI_OPERATION_NAME_VALUE_EXECUTE_TOOL;
|
|
488
|
+
const spanName = buildGenaiSpanName(opName, output);
|
|
489
|
+
const childSpan = tracer.startSpan(spanName, { startTime: startMs }, parentContext);
|
|
490
|
+
setMistralAgentTraceMarker(childSpan);
|
|
491
|
+
const toolArguments = output["arguments"];
|
|
492
|
+
const toolResult = output["info"];
|
|
493
|
+
setAvailableAttributes(childSpan, {
|
|
494
|
+
[ATTR_GEN_AI_OPERATION_NAME]: opName,
|
|
495
|
+
[ATTR_GEN_AI_PROVIDER_NAME]: GEN_AI_PROVIDER_NAME_VALUE_MISTRAL_AI,
|
|
496
|
+
[ATTR_GEN_AI_TOOL_CALL_ID]: output["id"],
|
|
497
|
+
[ATTR_GEN_AI_TOOL_CALL_ARGUMENTS]: stringifyToolAttribute(toolArguments),
|
|
498
|
+
[ATTR_GEN_AI_TOOL_CALL_RESULT]: stringifyToolAttribute(toolResult),
|
|
499
|
+
[ATTR_GEN_AI_TOOL_NAME]: output["name"],
|
|
500
|
+
[ATTR_GEN_AI_TOOL_TYPE]: "extension"
|
|
501
|
+
});
|
|
502
|
+
childSpan.end(endMs);
|
|
503
|
+
}
|
|
504
|
+
function createMessageOutputChildSpan(tracer, parentContext, output) {
|
|
505
|
+
const startMs = parseTimeToMillis(output["created_at"]);
|
|
506
|
+
const endMs = parseTimeToMillis(output["completed_at"]);
|
|
507
|
+
const opName = GEN_AI_OPERATION_NAME_VALUE_CHAT;
|
|
508
|
+
const spanName = buildGenaiSpanName(opName, output);
|
|
509
|
+
const childSpan = tracer.startSpan(spanName, { startTime: startMs }, parentContext);
|
|
510
|
+
setMistralAgentTraceMarker(childSpan);
|
|
511
|
+
const choiceWrapper = {
|
|
512
|
+
message: output,
|
|
513
|
+
finish_reason: output["finish_reason"] || ""
|
|
514
|
+
};
|
|
515
|
+
setAvailableAttributes(childSpan, {
|
|
516
|
+
[ATTR_GEN_AI_OPERATION_NAME]: opName,
|
|
517
|
+
[ATTR_GEN_AI_PROVIDER_NAME]: GEN_AI_PROVIDER_NAME_VALUE_MISTRAL_AI,
|
|
518
|
+
[ATTR_GEN_AI_RESPONSE_ID]: output["id"],
|
|
519
|
+
[ATTR_GEN_AI_AGENT_ID]: output["agent_id"],
|
|
520
|
+
[ATTR_GEN_AI_RESPONSE_MODEL]: output["model"],
|
|
521
|
+
[ATTR_GEN_AI_OUTPUT_MESSAGES]: JSON.stringify([formatOutputMessage(choiceWrapper)])
|
|
522
|
+
});
|
|
523
|
+
childSpan.end(endMs);
|
|
524
|
+
}
|
|
525
|
+
function enrichInvokeAgent(tracer, span, responseData) {
|
|
526
|
+
setAvailableAttributes(span, { [ATTR_GEN_AI_CONVERSATION_ID]: responseData["conversation_id"] });
|
|
527
|
+
const outputs = responseData["outputs"] || [];
|
|
528
|
+
const parentContext = trace.setSpan(context.active(), span);
|
|
529
|
+
for (const output of outputs) {
|
|
530
|
+
const outputType = output["type"];
|
|
531
|
+
if (!outputType) continue;
|
|
532
|
+
if (outputType === "function.call") continue;
|
|
533
|
+
if (outputType === "tool.execution") createToolExecutionChildSpan(tracer, parentContext, output);
|
|
534
|
+
else if (outputType === "message.output") createMessageOutputChildSpan(tracer, parentContext, output);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
function enrichOcr(span, responseData) {
|
|
538
|
+
const usageInfo = responseData["usage_info"];
|
|
539
|
+
if (!usageInfo) return;
|
|
540
|
+
setAvailableAttributes(span, {
|
|
541
|
+
[MistralAIAttributes.MISTRAL_AI_OCR_USAGE_PAGES_PROCESSED]: usageInfo["pages_processed"],
|
|
542
|
+
[MistralAIAttributes.MISTRAL_AI_OCR_USAGE_DOC_SIZE_BYTES]: usageInfo["doc_size_bytes"]
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
function enrichSpanFromResponse(tracer, span, operationId, responseData) {
|
|
546
|
+
const genAiOp = inferGenAiOperationName(operationId);
|
|
547
|
+
if (genAiOp === null) return;
|
|
548
|
+
enrichResponseGenaiAttrs(span, genAiOp, responseData);
|
|
549
|
+
if (genAiOp === GEN_AI_OPERATION_NAME_VALUE_CREATE_AGENT) enrichCreateAgent(span, responseData);
|
|
550
|
+
else if (genAiOp === GEN_AI_OPERATION_NAME_VALUE_INVOKE_AGENT) enrichInvokeAgent(tracer, span, responseData);
|
|
551
|
+
if (operationId === "ocr_v1_ocr_post") enrichOcr(span, responseData);
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Get a tracer from the registered or global TracerProvider.
|
|
555
|
+
*
|
|
556
|
+
* The SDK does not set up its own TracerProvider. It relies on the application
|
|
557
|
+
* to register one explicitly or configure OpenTelemetry's global provider.
|
|
558
|
+
*
|
|
559
|
+
* If no TracerProvider is configured, the ProxyTracerProvider (default) will
|
|
560
|
+
* return a NoOp tracer, effectively disabling tracing. Once the application
|
|
561
|
+
* sets up a real TracerProvider, subsequent spans will be recorded.
|
|
562
|
+
*/
|
|
563
|
+
function getOrCreateOtelTracer(provider, options = {}) {
|
|
564
|
+
return (provider ?? (options.useRegisteredProvider === false ? void 0 : getRegisteredTracerProvider()) ?? trace.getTracerProvider()).getTracer(MISTRAL_SDK_OTEL_TRACER_NAME);
|
|
565
|
+
}
|
|
566
|
+
function getSpanContext(span) {
|
|
567
|
+
return trace.setSpan(context.active(), span);
|
|
568
|
+
}
|
|
569
|
+
function runWithContext(context$1, fn) {
|
|
570
|
+
return context.with(context$1, fn);
|
|
571
|
+
}
|
|
572
|
+
async function recordRequestError(context, error) {
|
|
573
|
+
const span = trace.getSpan(context);
|
|
574
|
+
if (span) await getResponseAndError(span, null, error);
|
|
575
|
+
}
|
|
576
|
+
function warn(error, details) {
|
|
577
|
+
if (MISTRAL_SDK_DEBUG_TRACING) console.warn(error, details);
|
|
578
|
+
else console.warn(error, DEBUG_HINT);
|
|
579
|
+
}
|
|
580
|
+
async function getTracedRequestAndSpan(tracer, operationId, request) {
|
|
581
|
+
const span = tracer.startSpan(operationId);
|
|
582
|
+
if (!span.isRecording()) return {
|
|
583
|
+
request,
|
|
584
|
+
span,
|
|
585
|
+
body: null
|
|
586
|
+
};
|
|
587
|
+
try {
|
|
588
|
+
setMistralAgentTraceMarker(span);
|
|
589
|
+
const conversationId = propagation.getBaggage(context.active())?.getEntry(ATTR_GEN_AI_CONVERSATION_ID)?.value;
|
|
590
|
+
if (conversationId) span.setAttribute(ATTR_GEN_AI_CONVERSATION_ID, conversationId);
|
|
591
|
+
let body = null;
|
|
592
|
+
if (request.body && isKnownGenAiOperation(operationId) && isJsonContentType(request.headers.get("content-type"))) try {
|
|
593
|
+
body = await request.clone().text();
|
|
594
|
+
} catch {}
|
|
595
|
+
const headers = new Headers(request.headers);
|
|
596
|
+
const headerCarrier = {};
|
|
597
|
+
propagation.inject(trace.setSpan(context.active(), span), headerCarrier);
|
|
598
|
+
for (const [key, value] of Object.entries(headerCarrier)) headers.set(key, value);
|
|
599
|
+
const newRequest = new Request(request, { headers });
|
|
600
|
+
const url = new URL(request.url);
|
|
601
|
+
enrichSpanFromRequest(span, operationId, url, request.method, headers.get("host") || url.host, body);
|
|
602
|
+
return {
|
|
603
|
+
request: newRequest,
|
|
604
|
+
span,
|
|
605
|
+
body
|
|
606
|
+
};
|
|
607
|
+
} catch (err) {
|
|
608
|
+
warn(TracingErrors.FAILED_TO_CREATE_SPAN_FOR_REQUEST, err);
|
|
609
|
+
try {
|
|
610
|
+
span.end();
|
|
611
|
+
} catch {}
|
|
612
|
+
return {
|
|
613
|
+
request,
|
|
614
|
+
span,
|
|
615
|
+
body: null
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
async function getTracedResponse(tracer, span, operationId, response) {
|
|
620
|
+
if (!span.isRecording()) return response;
|
|
621
|
+
try {
|
|
622
|
+
span.setStatus({ code: SpanStatusCode.OK });
|
|
623
|
+
span.setAttribute(ATTR_HTTP_RESPONSE_STATUS_CODE, response.status);
|
|
624
|
+
const knownGenAiOperation = isKnownGenAiOperation(operationId);
|
|
625
|
+
const responseContentType = response.headers.get("content-type");
|
|
626
|
+
if (knownGenAiOperation && !response.bodyUsed && responseContentType?.toLowerCase().includes("text/event-stream") === true && response.body) return createTracedStreamResponse(response, span, tracer, operationId);
|
|
627
|
+
if (knownGenAiOperation && !response.bodyUsed && isJsonContentType(responseContentType)) {
|
|
628
|
+
const clonedResponse = response.clone();
|
|
629
|
+
try {
|
|
630
|
+
enrichSpanFromResponse(tracer, span, operationId, await clonedResponse.json());
|
|
631
|
+
} catch {}
|
|
632
|
+
}
|
|
633
|
+
endSpan(span);
|
|
634
|
+
return response;
|
|
635
|
+
} catch (err) {
|
|
636
|
+
warn(TracingErrors.FAILED_TO_ENRICH_SPAN_WITH_RESPONSE, err);
|
|
637
|
+
endSpan(span);
|
|
638
|
+
return response;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
function createTracedStreamResponse(response, span, tracer, operationId) {
|
|
642
|
+
const originalBody = response.body;
|
|
643
|
+
const chunks = [];
|
|
644
|
+
const decoder = new TextDecoder();
|
|
645
|
+
const reader = originalBody.getReader();
|
|
646
|
+
let finalized = false;
|
|
647
|
+
const finalize = () => {
|
|
648
|
+
if (finalized) return;
|
|
649
|
+
const remaining = decoder.decode();
|
|
650
|
+
if (remaining) chunks.push(remaining);
|
|
651
|
+
finalized = true;
|
|
652
|
+
finalizeStreamSpan(chunks, span, tracer, operationId);
|
|
653
|
+
};
|
|
654
|
+
const tracedStream = new ReadableStream({
|
|
655
|
+
async pull(controller) {
|
|
656
|
+
try {
|
|
657
|
+
const { done, value } = await reader.read();
|
|
658
|
+
if (done) {
|
|
659
|
+
finalize();
|
|
660
|
+
controller.close();
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
chunks.push(decoder.decode(value, { stream: true }));
|
|
664
|
+
controller.enqueue(value);
|
|
665
|
+
} catch (err) {
|
|
666
|
+
finalize();
|
|
667
|
+
controller.error(err);
|
|
668
|
+
try {
|
|
669
|
+
await reader.cancel(err);
|
|
670
|
+
} catch {}
|
|
671
|
+
}
|
|
672
|
+
},
|
|
673
|
+
async cancel(reason) {
|
|
674
|
+
finalize();
|
|
675
|
+
await reader.cancel(reason);
|
|
676
|
+
}
|
|
677
|
+
}, { highWaterMark: 0 });
|
|
678
|
+
return new Response(tracedStream, {
|
|
679
|
+
status: response.status,
|
|
680
|
+
statusText: response.statusText,
|
|
681
|
+
headers: response.headers
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
function finalizeStreamSpan(chunks, span, tracer, operationId) {
|
|
685
|
+
try {
|
|
686
|
+
const parsedChunks = parseSseChunks(chunks.join(""));
|
|
687
|
+
if (parsedChunks.length > 0) enrichSpanFromResponse(tracer, span, operationId, accumulateChunksToResponseDict(parsedChunks));
|
|
688
|
+
} catch (err) {
|
|
689
|
+
warn("Failed to enrich span with streaming response.", err);
|
|
690
|
+
}
|
|
691
|
+
endSpan(span);
|
|
692
|
+
}
|
|
693
|
+
async function getResponseAndError(span, response, error) {
|
|
694
|
+
if (!span.isRecording()) return {
|
|
695
|
+
response,
|
|
696
|
+
error
|
|
697
|
+
};
|
|
698
|
+
try {
|
|
699
|
+
if (error) {
|
|
700
|
+
span.recordException(error);
|
|
701
|
+
span.setStatus({
|
|
702
|
+
code: SpanStatusCode.ERROR,
|
|
703
|
+
message: String(error)
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
if (!response) {
|
|
707
|
+
endSpan(span);
|
|
708
|
+
return {
|
|
709
|
+
response,
|
|
710
|
+
error
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
try {
|
|
714
|
+
const body = await response.clone().json();
|
|
715
|
+
if (body["object"] === "error") {
|
|
716
|
+
const errorMsg = body["message"] || "";
|
|
717
|
+
const errorType = body["type"] || "";
|
|
718
|
+
if (errorMsg) {
|
|
719
|
+
span.setStatus({
|
|
720
|
+
code: SpanStatusCode.ERROR,
|
|
721
|
+
message: errorMsg
|
|
722
|
+
});
|
|
723
|
+
span.addEvent("exception", {
|
|
724
|
+
"exception.type": errorType || "api_error",
|
|
725
|
+
"exception.message": errorMsg
|
|
726
|
+
});
|
|
727
|
+
const attrs = { [ATTR_HTTP_RESPONSE_STATUS_CODE]: response.status };
|
|
728
|
+
if (errorType) attrs[ATTR_ERROR_TYPE] = errorType;
|
|
729
|
+
if (body["code"]) attrs[MistralAIAttributes.MISTRAL_AI_ERROR_CODE] = body["code"];
|
|
730
|
+
setAvailableAttributes(span, attrs);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
} catch {}
|
|
734
|
+
endSpan(span);
|
|
735
|
+
} catch (err) {
|
|
736
|
+
warn(TracingErrors.FAILED_TO_HANDLE_ERROR_IN_SPAN, err);
|
|
737
|
+
try {
|
|
738
|
+
span.end();
|
|
739
|
+
} catch {}
|
|
740
|
+
}
|
|
741
|
+
return {
|
|
742
|
+
response,
|
|
743
|
+
error
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
function endSpan(span) {
|
|
747
|
+
try {
|
|
748
|
+
span.end();
|
|
749
|
+
} catch (err) {
|
|
750
|
+
warn(TracingErrors.FAILED_TO_END_SPAN, err);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
/**
|
|
754
|
+
* Create a traced span using a callback pattern.
|
|
755
|
+
* This is the TypeScript equivalent of Python's context manager.
|
|
756
|
+
*/
|
|
757
|
+
async function traceAsync(name, fn) {
|
|
758
|
+
const span = getOrCreateOtelTracer().startSpan(name);
|
|
759
|
+
try {
|
|
760
|
+
return await fn(span);
|
|
761
|
+
} finally {
|
|
762
|
+
span.end();
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
//#endregion
|
|
766
|
+
export { MISTRAL_SDK_OTEL_TRACER_NAME, MistralAIAttributes, OTEL_SERVICE_NAME, TracingErrors, enrichSpanFromRequest, enrichSpanFromResponse, getOrCreateOtelTracer, getRegisteredTracerProvider, getResponseAndError, getSpanContext, getTracedRequestAndSpan, getTracedResponse, recordRequestError, registerTracerProvider, runWithContext, semConvAttributes, traceAsync };
|