Debian Codegraph @

src/anthropic/lib/_stainless_helpers.py

raw
1 """Tracking for SDK helper usage via the x-stainless-helper header.
2
3 This module is the single source of truth for the helper-telemetry header
4 keys and the closed tag vocabulary. The append-don't-clobber merge for the
5 header itself lives in `anthropic._base_client.merge_headers`; here
6 we only carry the constants and the per-object tagging machinery.
7 """
8
9 from __future__ import annotations
10
11 from typing import Any, Dict, Mapping, TypeVar, cast
12 from typing_extensions import Literal
13
14 __all__ = [
15 "STAINLESS_HELPER_HEADER",
16 "STAINLESS_HELPER_METHOD_HEADER",
17 "STAINLESS_STREAM_HELPER_HEADER",
18 "HELPER_METHOD_STREAM",
19 "StainlessHelperHeaderValue",
20 "helper_header",
21 "tag_helper",
22 "get_helper_tag",
23 "carry_helper_tag",
24 "collect_helpers",
25 "stainless_helper_header",
26 "stainless_helper_header_from_file",
27 ]
28
29
30 STAINLESS_HELPER_HEADER = "x-stainless-helper"
31 """Telemetry header naming the SDK helper(s) a request came from.
32
33 Always this lowercase form. `merge_headers` matches this key
34 case-insensitively for its append semantics, but a single canonical casing
35 keeps every call site greppable and avoids two literal casings of the same
36 key reaching a plain dict merge anywhere upstream of it.
37 """
38
39 STAINLESS_HELPER_METHOD_HEADER = "x-stainless-helper-method"
40 """Telemetry header naming the SDK method (e.g. `stream`) in use."""
41
42 STAINLESS_STREAM_HELPER_HEADER = "x-stainless-stream-helper"
43 """Telemetry header naming the streaming surface (e.g. `beta.messages`)."""
44
45 HELPER_METHOD_STREAM = "stream"
46
47
48 StainlessHelperHeaderValue = Literal[
49 "beta.messages.parse",
50 "BetaToolRunner",
51 "compaction",
52 "environments-work-poller",
53 "environments-worker",
54 "fallback-refusal-middleware",
55 "mcp_content",
56 "mcp_message",
57 "mcp_resource_to_content",
58 "mcp_resource_to_file",
59 "mcp_tool",
60 "messages.parse",
61 "session-tool-runner",
62 ]
63 """The closed set of helper telemetry tags, shared verbatim across SDKs.
64
65 Constrained so a typo at any call site is a type error rather than silently
66 mistagged telemetry. Existing values keep their original spellings — telemetry
67 consumers match on them, so renames lose history. New tags are hyphenated
68 lowercase; add them here (and to the matching set in every other SDK) before
69 using them.
70 """
71
72
73 def helper_header(value: StainlessHelperHeaderValue) -> dict[str, str]:
74 """The `x-stainless-helper: <value>` header dict, for passing into a
75 `merge_headers` call or as `extra_headers`/`default_headers`.
76
77 Typing keeps the value drawn from the closed vocabulary above.
78 """
79 return {STAINLESS_HELPER_HEADER: value}
80
81
82 _HELPER_ATTR = "_stainless_helper"
83
84
85 def tag_helper(obj: Any, name: StainlessHelperHeaderValue) -> None:
86 """Mark an object as created by a named SDK helper."""
87 try:
88 object.__setattr__(obj, _HELPER_ATTR, name)
89 except (AttributeError, TypeError):
90 pass
91
92
93 def get_helper_tag(obj: object) -> str | None:
94 """Get the helper name from an object, if any."""
95 return getattr(obj, _HELPER_ATTR, None) # type: ignore[return-value]
96
97
98 _MappingT = TypeVar("_MappingT", bound="Mapping[str, object]")
99
100
101 class _TaggedDict(Dict[str, Any]):
102 """A plain `dict` rejects `object.__setattr__`; this subclass can carry the tag."""
103
104
105 def carry_helper_tag(source: object, params: _MappingT) -> _MappingT:
106 """Return `params` carrying `source`'s helper tag, so the tag survives serializing a tagged object."""
107 tag = get_helper_tag(source)
108 if tag is None:
109 return params
110 tagged = _TaggedDict(params)
111 object.__setattr__(tagged, _HELPER_ATTR, tag)
112 return cast(_MappingT, tagged)
113
114
115 def collect_helpers(
116 tools: Any = None,
117 messages: Any = None,
118 ) -> list[str]:
119 """Collect deduplicated helper names from tools and messages."""
120 helpers: list[str] = []
121
122 def _add(tag: str | None) -> None:
123 if tag is not None and tag not in helpers:
124 helpers.append(tag)
125
126 if tools:
127 for tool in tools:
128 _add(get_helper_tag(tool))
129
130 if messages:
131 for message in messages:
132 _add(get_helper_tag(message))
133
134 if isinstance(message, dict):
135 blocks: Any = cast(dict[str, Any], message).get("content")
136 else:
137 blocks = getattr(message, "content", None)
138 if isinstance(blocks, list):
139 for block in cast(list[object], blocks):
140 _add(get_helper_tag(block))
141
142 return helpers
143
144
145 def stainless_helper_header(
146 tools: Any = None,
147 messages: Any = None,
148 ) -> dict[str, str]:
149 """Build x-stainless-helper header dict from tools and messages.
150
151 Returns an empty dict if no helpers are found.
152 """
153 helpers = collect_helpers(tools, messages)
154 if not helpers:
155 return {}
156 return {STAINLESS_HELPER_HEADER: ", ".join(helpers)}
157
158
159 def stainless_helper_header_from_file(file: object) -> dict[str, str]:
160 """Build x-stainless-helper header dict from a file object."""
161 tag = get_helper_tag(file)
162 if tag is None:
163 return {}
164 return {STAINLESS_HELPER_HEADER: tag}