telemetry-dev-openrouter 0.2.5__tar.gz → 0.2.7__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: telemetry-dev-openrouter
3
- Version: 0.2.5
3
+ Version: 0.2.7
4
4
  Summary: OpenRouter integration for telemetry.dev Python SDK
5
5
  Keywords: telemetry,opentelemetry,openrouter,llm,genai,tracing
6
6
  Author: telemetry.dev
@@ -97,6 +97,10 @@ input, supported sampling parameters, response model and ID, finish reasons, out
97
97
  token usage. Embedding spans capture the request input, request and response models, and token
98
98
  usage; embedding vectors are intentionally not captured as output.
99
99
 
100
+ Generation spans also list the request's tools in `gen_ai.tool.definitions`: each tool's type and
101
+ name, and with `capture_input` on the description and parameters of each function and custom tool
102
+ (a custom tool's input format), which pass through `mask`.
103
+
100
104
  When OpenRouter returns cost information, the integration records `gen_ai.usage.cost` from
101
105
  `usage.cost`. If that field is absent, it falls back to
102
106
  `usage.cost_details.upstream_inference_cost`. The cost attribute is omitted when neither value is
@@ -74,6 +74,10 @@ input, supported sampling parameters, response model and ID, finish reasons, out
74
74
  token usage. Embedding spans capture the request input, request and response models, and token
75
75
  usage; embedding vectors are intentionally not captured as output.
76
76
 
77
+ Generation spans also list the request's tools in `gen_ai.tool.definitions`: each tool's type and
78
+ name, and with `capture_input` on the description and parameters of each function and custom tool
79
+ (a custom tool's input format), which pass through `mask`.
80
+
77
81
  When OpenRouter returns cost information, the integration records `gen_ai.usage.cost` from
78
82
  `usage.cost`. If that field is absent, it falls back to
79
83
  `usage.cost_details.upstream_inference_cost`. The cost attribute is omitted when neither value is
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telemetry-dev-openrouter"
3
- version = "0.2.5"
3
+ version = "0.2.7"
4
4
  description = "OpenRouter integration for telemetry.dev Python SDK"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "telemetry-dev-openrouter"
3
- version = "0.2.5"
3
+ version = "0.2.7"
4
4
  description = "OpenRouter integration for telemetry.dev Python SDK"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -14,8 +14,9 @@ import telemetry_dev
14
14
  from openrouter.chat import Chat
15
15
  from openrouter.embeddings import Embeddings
16
16
  from openrouter.responses import Responses
17
+ from telemetry_dev._serialize import json_dumps
17
18
 
18
- __version__ = "0.2.5"
19
+ __version__ = "0.2.7"
19
20
 
20
21
  RequestMapper = Callable[[Mapping[str, Any]], tuple[str, dict[str, Any]]]
21
22
  ResponseMapper = Callable[[Any], dict[str, Any]]
@@ -196,6 +197,39 @@ def _prompt_attributes(messages: object) -> dict[str, Any]:
196
197
  return cast("dict[str, Any]", read(messages)) if callable(read) else {}
197
198
 
198
199
 
200
+ def _tool_definitions(tools: Any) -> dict[str, str] | None:
201
+ """The request tools, in the OpenAI format, as ``gen_ai.tool.definitions``: each tool's type
202
+ and name, and with input capture on a function or custom tool's description and its
203
+ parameters (custom tools: their input format). Chat Completions nests a tool under
204
+ ``function`` or ``custom``; Responses puts it at the top. A built-in tool without a name is
205
+ listed by its type. The core SDK also strips descriptions and schemas with capture off; this
206
+ check keeps them out with a core older than that rule."""
207
+ client = telemetry_dev.get_client()
208
+ content = client is not None and client.capture_input
209
+ definitions: list[dict[str, Any]] = []
210
+ for tool in _sequence_items(tools):
211
+ kind = _string(_field(tool, "type"))
212
+ if kind is None:
213
+ continue
214
+ spec = _field(tool, "custom" if kind == "custom" else "function") or tool
215
+ name = _string(_field(spec, "name"))
216
+ if kind not in ("function", "custom"):
217
+ definitions.append({"type": kind} if name is None else {"type": kind, "name": name})
218
+ continue
219
+ if name is None:
220
+ continue
221
+ definition: dict[str, Any] = {"type": kind, "name": name}
222
+ if content:
223
+ description = _string(_field(spec, "description"))
224
+ if description is not None:
225
+ definition["description"] = description
226
+ parameters = _field(spec, "format" if kind == "custom" else "parameters")
227
+ if parameters is not None:
228
+ definition["parameters"] = parameters
229
+ definitions.append(definition)
230
+ return {"gen_ai.tool.definitions": _tools_json(definitions)} if definitions else None
231
+
232
+
199
233
  def _chat_request(params: Mapping[str, Any]) -> tuple[str, dict[str, Any]]:
200
234
  model = _string(params.get("model"))
201
235
  max_completion_tokens = _number(params.get("max_completion_tokens"))
@@ -215,7 +249,11 @@ def _chat_request(params: Mapping[str, Any]) -> tuple[str, dict[str, Any]]:
215
249
  "seed": _number(params.get("seed")),
216
250
  "frequency_penalty": _number(params.get("frequency_penalty")),
217
251
  "presence_penalty": _number(params.get("presence_penalty")),
218
- "attributes": _prompt_attributes(params.get("messages")) or None,
252
+ "attributes": {
253
+ **(_tool_definitions(params.get("tools")) or {}),
254
+ **_prompt_attributes(params.get("messages")),
255
+ }
256
+ or None,
219
257
  },
220
258
  )
221
259
 
@@ -283,7 +321,11 @@ def _responses_request(params: Mapping[str, Any]) -> tuple[str, dict[str, Any]]:
283
321
  "max_tokens": _number(params.get("max_output_tokens")),
284
322
  "frequency_penalty": _number(params.get("frequency_penalty")),
285
323
  "presence_penalty": _number(params.get("presence_penalty")),
286
- "attributes": _prompt_attributes(params.get("input")) or None,
324
+ "attributes": {
325
+ **(_tool_definitions(params.get("tools")) or {}),
326
+ **_prompt_attributes(params.get("input")),
327
+ }
328
+ or None,
287
329
  },
288
330
  )
289
331
 
@@ -303,44 +345,56 @@ def _responses_usage(raw: Any) -> dict[str, int | float] | None:
303
345
  )
304
346
 
305
347
 
306
- def _response_failed_error(response: Any) -> RuntimeError:
348
+ def _failure_code(value: Any) -> str | int | None:
349
+ # OpenRouter's numeric codes are HTTP statuses, which the core SDK records as one.
350
+ if isinstance(value, int) and not isinstance(value, bool):
351
+ return value
352
+ return value if isinstance(value, str) else None
353
+
354
+
355
+ def _provider_failure(message: str, code: str | int | None, kind: str | None) -> Exception:
356
+ # A failure that OpenRouter reports in a response body or a stream event, not as an HTTP
357
+ # error. The core SDK records its `code` in error.type (a number counts as an HTTP status, such
358
+ # as 429), else its `type`, because a plain Exception names no cause; see _error_type in
359
+ # telemetry_dev/_spans.py.
360
+ error = Exception(message)
361
+ vars(error).update(code=code, type=kind)
362
+ return error
363
+
364
+
365
+ def _response_failed_error(response: Any) -> Exception:
307
366
  error = _field(response, "error")
308
367
  if error is None:
309
- return RuntimeError("response.failed")
310
- code = _error_code(_field(error, "code"))
368
+ return _provider_failure("response.failed", None, "response.failed")
369
+ raw_code = _field(error, "code")
370
+ code = _error_code(raw_code)
311
371
  message = _string(_field(error, "message"))
312
- if code and message:
313
- return RuntimeError(f"response.failed: {code}: {message}")
314
- if code:
315
- return RuntimeError(f"response.failed: {code}")
316
- if message:
317
- return RuntimeError(f"response.failed: {message}")
318
- return RuntimeError("response.failed")
372
+ text = ": ".join(part for part in ("response.failed", code, message) if part)
373
+ return _provider_failure(text, _failure_code(raw_code), "response.failed")
319
374
 
320
375
 
321
- def _response_stream_error(event: Any) -> RuntimeError:
322
- code = _error_code(_field(event, "code"))
376
+ def _response_stream_error(event: Any) -> Exception:
377
+ raw_code = _field(event, "code")
378
+ code = _error_code(raw_code)
323
379
  message = _string(_field(event, "message"))
324
- if code and message:
325
- return RuntimeError(f"response.error: {code}: {message}")
326
- if code:
327
- return RuntimeError(f"response.error: {code}")
328
- if message:
329
- return RuntimeError(f"response.error: {message}")
330
- return RuntimeError("response.error")
380
+ text = ": ".join(part for part in ("response.error", code, message) if part)
381
+ return _provider_failure(text, _failure_code(raw_code), "response.error")
331
382
 
332
383
 
333
- def _chunk_error(chunk: Any) -> RuntimeError | None:
384
+ def _chunk_error(chunk: Any) -> Exception | None:
334
385
  error = _field(chunk, "error")
335
386
  if error is None:
336
387
  return None
337
- code = _error_code(_field(error, "code"))
388
+ raw_code = _field(error, "code")
389
+ code = _error_code(raw_code)
338
390
  message = _string(_field(error, "message"))
339
391
  if code and message:
340
- return RuntimeError(f"stream error {code}: {message}")
341
- if message:
342
- return RuntimeError(f"stream error: {message}")
343
- return RuntimeError(f"stream error {code}" if code else "stream error")
392
+ text = f"stream error {code}: {message}"
393
+ elif message:
394
+ text = f"stream error: {message}"
395
+ else:
396
+ text = f"stream error {code}" if code else "stream error"
397
+ return _provider_failure(text, _failure_code(raw_code), "stream error")
344
398
 
345
399
 
346
400
  def _responses_response(
@@ -1982,3 +2036,14 @@ __all__ = [
1982
2036
  "uninstrument_openrouter",
1983
2037
  "wrap_open_router",
1984
2038
  ]
2039
+
2040
+
2041
+ def _tools_json(definitions: list[dict[str, Any]]) -> str:
2042
+ """The definitions as JSON, or only their types and names when a schema cannot be
2043
+ serialized, such as one holding a cycle: the wrapper maps the request outside any catch."""
2044
+ try:
2045
+ return json_dumps(definitions)
2046
+ except (TypeError, ValueError):
2047
+ return json_dumps(
2048
+ [{key: tool[key] for key in ("type", "name") if key in tool} for tool in definitions]
2049
+ )