judgeval 0.0.11__py3-none-any.whl → 0.22.2__py3-none-any.whl

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.

Potentially problematic release.


This version of judgeval might be problematic. Click here for more details.

Files changed (171) hide show
  1. judgeval/__init__.py +177 -12
  2. judgeval/api/__init__.py +519 -0
  3. judgeval/api/api_types.py +407 -0
  4. judgeval/cli.py +79 -0
  5. judgeval/constants.py +76 -47
  6. judgeval/data/__init__.py +3 -3
  7. judgeval/data/evaluation_run.py +125 -0
  8. judgeval/data/example.py +15 -56
  9. judgeval/data/judgment_types.py +450 -0
  10. judgeval/data/result.py +29 -73
  11. judgeval/data/scorer_data.py +29 -62
  12. judgeval/data/scripts/fix_default_factory.py +23 -0
  13. judgeval/data/scripts/openapi_transform.py +123 -0
  14. judgeval/data/trace.py +121 -0
  15. judgeval/dataset/__init__.py +264 -0
  16. judgeval/env.py +52 -0
  17. judgeval/evaluation/__init__.py +344 -0
  18. judgeval/exceptions.py +27 -0
  19. judgeval/integrations/langgraph/__init__.py +13 -0
  20. judgeval/integrations/openlit/__init__.py +50 -0
  21. judgeval/judges/__init__.py +2 -3
  22. judgeval/judges/base_judge.py +2 -3
  23. judgeval/judges/litellm_judge.py +100 -20
  24. judgeval/judges/together_judge.py +101 -20
  25. judgeval/judges/utils.py +20 -24
  26. judgeval/logger.py +62 -0
  27. judgeval/prompt/__init__.py +330 -0
  28. judgeval/scorers/__init__.py +18 -25
  29. judgeval/scorers/agent_scorer.py +17 -0
  30. judgeval/scorers/api_scorer.py +45 -41
  31. judgeval/scorers/base_scorer.py +83 -38
  32. judgeval/scorers/example_scorer.py +17 -0
  33. judgeval/scorers/exceptions.py +1 -0
  34. judgeval/scorers/judgeval_scorers/__init__.py +0 -148
  35. judgeval/scorers/judgeval_scorers/api_scorers/__init__.py +19 -17
  36. judgeval/scorers/judgeval_scorers/api_scorers/answer_correctness.py +13 -19
  37. judgeval/scorers/judgeval_scorers/api_scorers/answer_relevancy.py +12 -19
  38. judgeval/scorers/judgeval_scorers/api_scorers/faithfulness.py +13 -19
  39. judgeval/scorers/judgeval_scorers/api_scorers/instruction_adherence.py +15 -0
  40. judgeval/scorers/judgeval_scorers/api_scorers/prompt_scorer.py +327 -0
  41. judgeval/scorers/score.py +77 -306
  42. judgeval/scorers/utils.py +4 -199
  43. judgeval/tracer/__init__.py +1122 -2
  44. judgeval/tracer/constants.py +1 -0
  45. judgeval/tracer/exporters/__init__.py +40 -0
  46. judgeval/tracer/exporters/s3.py +119 -0
  47. judgeval/tracer/exporters/store.py +59 -0
  48. judgeval/tracer/exporters/utils.py +32 -0
  49. judgeval/tracer/keys.py +63 -0
  50. judgeval/tracer/llm/__init__.py +7 -0
  51. judgeval/tracer/llm/config.py +78 -0
  52. judgeval/tracer/llm/constants.py +9 -0
  53. judgeval/tracer/llm/llm_anthropic/__init__.py +3 -0
  54. judgeval/tracer/llm/llm_anthropic/config.py +6 -0
  55. judgeval/tracer/llm/llm_anthropic/messages.py +452 -0
  56. judgeval/tracer/llm/llm_anthropic/messages_stream.py +322 -0
  57. judgeval/tracer/llm/llm_anthropic/wrapper.py +59 -0
  58. judgeval/tracer/llm/llm_google/__init__.py +3 -0
  59. judgeval/tracer/llm/llm_google/config.py +6 -0
  60. judgeval/tracer/llm/llm_google/generate_content.py +127 -0
  61. judgeval/tracer/llm/llm_google/wrapper.py +30 -0
  62. judgeval/tracer/llm/llm_openai/__init__.py +3 -0
  63. judgeval/tracer/llm/llm_openai/beta_chat_completions.py +216 -0
  64. judgeval/tracer/llm/llm_openai/chat_completions.py +501 -0
  65. judgeval/tracer/llm/llm_openai/config.py +6 -0
  66. judgeval/tracer/llm/llm_openai/responses.py +506 -0
  67. judgeval/tracer/llm/llm_openai/utils.py +42 -0
  68. judgeval/tracer/llm/llm_openai/wrapper.py +63 -0
  69. judgeval/tracer/llm/llm_together/__init__.py +3 -0
  70. judgeval/tracer/llm/llm_together/chat_completions.py +406 -0
  71. judgeval/tracer/llm/llm_together/config.py +6 -0
  72. judgeval/tracer/llm/llm_together/wrapper.py +52 -0
  73. judgeval/tracer/llm/providers.py +19 -0
  74. judgeval/tracer/managers.py +167 -0
  75. judgeval/tracer/processors/__init__.py +220 -0
  76. judgeval/tracer/utils.py +19 -0
  77. judgeval/trainer/__init__.py +14 -0
  78. judgeval/trainer/base_trainer.py +122 -0
  79. judgeval/trainer/config.py +128 -0
  80. judgeval/trainer/console.py +144 -0
  81. judgeval/trainer/fireworks_trainer.py +396 -0
  82. judgeval/trainer/trainable_model.py +243 -0
  83. judgeval/trainer/trainer.py +70 -0
  84. judgeval/utils/async_utils.py +39 -0
  85. judgeval/utils/decorators/__init__.py +0 -0
  86. judgeval/utils/decorators/dont_throw.py +37 -0
  87. judgeval/utils/decorators/use_once.py +13 -0
  88. judgeval/utils/file_utils.py +97 -0
  89. judgeval/utils/guards.py +36 -0
  90. judgeval/utils/meta.py +27 -0
  91. judgeval/utils/project.py +15 -0
  92. judgeval/utils/serialize.py +253 -0
  93. judgeval/utils/testing.py +70 -0
  94. judgeval/utils/url.py +10 -0
  95. judgeval/utils/version_check.py +28 -0
  96. judgeval/utils/wrappers/README.md +3 -0
  97. judgeval/utils/wrappers/__init__.py +15 -0
  98. judgeval/utils/wrappers/immutable_wrap_async.py +74 -0
  99. judgeval/utils/wrappers/immutable_wrap_async_iterator.py +84 -0
  100. judgeval/utils/wrappers/immutable_wrap_sync.py +66 -0
  101. judgeval/utils/wrappers/immutable_wrap_sync_iterator.py +84 -0
  102. judgeval/utils/wrappers/mutable_wrap_async.py +67 -0
  103. judgeval/utils/wrappers/mutable_wrap_sync.py +67 -0
  104. judgeval/utils/wrappers/py.typed +0 -0
  105. judgeval/utils/wrappers/utils.py +35 -0
  106. judgeval/version.py +5 -0
  107. judgeval/warnings.py +4 -0
  108. judgeval-0.22.2.dist-info/METADATA +265 -0
  109. judgeval-0.22.2.dist-info/RECORD +112 -0
  110. judgeval-0.22.2.dist-info/entry_points.txt +2 -0
  111. judgeval/clients.py +0 -39
  112. judgeval/common/__init__.py +0 -8
  113. judgeval/common/exceptions.py +0 -28
  114. judgeval/common/logger.py +0 -189
  115. judgeval/common/tracer.py +0 -798
  116. judgeval/common/utils.py +0 -763
  117. judgeval/data/api_example.py +0 -111
  118. judgeval/data/datasets/__init__.py +0 -5
  119. judgeval/data/datasets/dataset.py +0 -286
  120. judgeval/data/datasets/eval_dataset_client.py +0 -193
  121. judgeval/data/datasets/ground_truth.py +0 -54
  122. judgeval/data/datasets/utils.py +0 -74
  123. judgeval/evaluation_run.py +0 -132
  124. judgeval/judges/mixture_of_judges.py +0 -248
  125. judgeval/judgment_client.py +0 -354
  126. judgeval/run_evaluation.py +0 -439
  127. judgeval/scorers/judgeval_scorer.py +0 -140
  128. judgeval/scorers/judgeval_scorers/api_scorers/contextual_precision.py +0 -19
  129. judgeval/scorers/judgeval_scorers/api_scorers/contextual_recall.py +0 -19
  130. judgeval/scorers/judgeval_scorers/api_scorers/contextual_relevancy.py +0 -22
  131. judgeval/scorers/judgeval_scorers/api_scorers/hallucination.py +0 -19
  132. judgeval/scorers/judgeval_scorers/api_scorers/json_correctness.py +0 -32
  133. judgeval/scorers/judgeval_scorers/api_scorers/summarization.py +0 -20
  134. judgeval/scorers/judgeval_scorers/api_scorers/tool_correctness.py +0 -19
  135. judgeval/scorers/judgeval_scorers/classifiers/__init__.py +0 -3
  136. judgeval/scorers/judgeval_scorers/classifiers/text2sql/__init__.py +0 -3
  137. judgeval/scorers/judgeval_scorers/classifiers/text2sql/text2sql_scorer.py +0 -54
  138. judgeval/scorers/judgeval_scorers/local_implementations/__init__.py +0 -24
  139. judgeval/scorers/judgeval_scorers/local_implementations/answer_correctness/__init__.py +0 -4
  140. judgeval/scorers/judgeval_scorers/local_implementations/answer_correctness/answer_correctness_scorer.py +0 -277
  141. judgeval/scorers/judgeval_scorers/local_implementations/answer_correctness/prompts.py +0 -169
  142. judgeval/scorers/judgeval_scorers/local_implementations/answer_relevancy/__init__.py +0 -4
  143. judgeval/scorers/judgeval_scorers/local_implementations/answer_relevancy/answer_relevancy_scorer.py +0 -298
  144. judgeval/scorers/judgeval_scorers/local_implementations/answer_relevancy/prompts.py +0 -174
  145. judgeval/scorers/judgeval_scorers/local_implementations/contextual_precision/__init__.py +0 -3
  146. judgeval/scorers/judgeval_scorers/local_implementations/contextual_precision/contextual_precision_scorer.py +0 -264
  147. judgeval/scorers/judgeval_scorers/local_implementations/contextual_precision/prompts.py +0 -106
  148. judgeval/scorers/judgeval_scorers/local_implementations/contextual_recall/__init__.py +0 -3
  149. judgeval/scorers/judgeval_scorers/local_implementations/contextual_recall/contextual_recall_scorer.py +0 -254
  150. judgeval/scorers/judgeval_scorers/local_implementations/contextual_recall/prompts.py +0 -142
  151. judgeval/scorers/judgeval_scorers/local_implementations/contextual_relevancy/__init__.py +0 -3
  152. judgeval/scorers/judgeval_scorers/local_implementations/contextual_relevancy/contextual_relevancy_scorer.py +0 -245
  153. judgeval/scorers/judgeval_scorers/local_implementations/contextual_relevancy/prompts.py +0 -121
  154. judgeval/scorers/judgeval_scorers/local_implementations/faithfulness/__init__.py +0 -3
  155. judgeval/scorers/judgeval_scorers/local_implementations/faithfulness/faithfulness_scorer.py +0 -325
  156. judgeval/scorers/judgeval_scorers/local_implementations/faithfulness/prompts.py +0 -268
  157. judgeval/scorers/judgeval_scorers/local_implementations/hallucination/__init__.py +0 -3
  158. judgeval/scorers/judgeval_scorers/local_implementations/hallucination/hallucination_scorer.py +0 -263
  159. judgeval/scorers/judgeval_scorers/local_implementations/hallucination/prompts.py +0 -104
  160. judgeval/scorers/judgeval_scorers/local_implementations/json_correctness/__init__.py +0 -5
  161. judgeval/scorers/judgeval_scorers/local_implementations/json_correctness/json_correctness_scorer.py +0 -134
  162. judgeval/scorers/judgeval_scorers/local_implementations/summarization/__init__.py +0 -3
  163. judgeval/scorers/judgeval_scorers/local_implementations/summarization/prompts.py +0 -247
  164. judgeval/scorers/judgeval_scorers/local_implementations/summarization/summarization_scorer.py +0 -550
  165. judgeval/scorers/judgeval_scorers/local_implementations/tool_correctness/__init__.py +0 -3
  166. judgeval/scorers/judgeval_scorers/local_implementations/tool_correctness/tool_correctness_scorer.py +0 -157
  167. judgeval/scorers/prompt_scorer.py +0 -439
  168. judgeval-0.0.11.dist-info/METADATA +0 -36
  169. judgeval-0.0.11.dist-info/RECORD +0 -84
  170. {judgeval-0.0.11.dist-info → judgeval-0.22.2.dist-info}/WHEEL +0 -0
  171. {judgeval-0.0.11.dist-info → judgeval-0.22.2.dist-info}/licenses/LICENSE.md +0 -0
@@ -0,0 +1,452 @@
1
+ from __future__ import annotations
2
+ from typing import (
3
+ TYPE_CHECKING,
4
+ Any,
5
+ Awaitable,
6
+ Callable,
7
+ Dict,
8
+ Iterator,
9
+ AsyncIterator,
10
+ Generator,
11
+ AsyncGenerator,
12
+ Tuple,
13
+ )
14
+
15
+ from judgeval.tracer.keys import AttributeKeys
16
+ from judgeval.tracer.utils import set_span_attribute
17
+ from judgeval.utils.serialize import safe_serialize
18
+ from judgeval.utils.wrappers import (
19
+ immutable_wrap_sync,
20
+ immutable_wrap_async,
21
+ mutable_wrap_sync,
22
+ mutable_wrap_async,
23
+ immutable_wrap_sync_iterator,
24
+ immutable_wrap_async_iterator,
25
+ )
26
+
27
+ if TYPE_CHECKING:
28
+ from judgeval.tracer import Tracer
29
+ from anthropic import Anthropic, AsyncAnthropic
30
+ from anthropic.types import (
31
+ Message,
32
+ Usage,
33
+ MessageDeltaUsage,
34
+ RawMessageStreamEvent,
35
+ )
36
+
37
+
38
+ def _extract_anthropic_content(chunk: RawMessageStreamEvent) -> str:
39
+ if chunk.type == "content_block_delta":
40
+ delta = chunk.delta
41
+ if delta.type == "text_delta" and delta.text:
42
+ return delta.text
43
+ return ""
44
+
45
+
46
+ def _extract_anthropic_tokens(
47
+ usage: Usage | MessageDeltaUsage,
48
+ ) -> Tuple[int, int, int, int]:
49
+ input_tokens = usage.input_tokens if usage.input_tokens is not None else 0
50
+ output_tokens = usage.output_tokens if usage.output_tokens is not None else 0
51
+ cache_read = (
52
+ usage.cache_read_input_tokens
53
+ if usage.cache_read_input_tokens is not None
54
+ else 0
55
+ )
56
+ cache_creation = (
57
+ usage.cache_creation_input_tokens
58
+ if usage.cache_creation_input_tokens is not None
59
+ else 0
60
+ )
61
+ return (input_tokens, output_tokens, cache_read, cache_creation)
62
+
63
+
64
+ def _extract_anthropic_chunk_usage(
65
+ chunk: RawMessageStreamEvent,
66
+ ) -> Usage | MessageDeltaUsage | None:
67
+ if chunk.type == "message_start":
68
+ return chunk.message.usage if chunk.message else None
69
+ elif chunk.type == "message_delta":
70
+ return chunk.usage if hasattr(chunk, "usage") else None
71
+ return None
72
+
73
+
74
+ def wrap_messages_create_sync(tracer: Tracer, client: Anthropic) -> None:
75
+ original_func = client.messages.create
76
+
77
+ def dispatcher(*args: Any, **kwargs: Any) -> Any:
78
+ if kwargs.get("stream", False):
79
+ return _wrap_streaming_sync(tracer, original_func)(*args, **kwargs)
80
+ return _wrap_non_streaming_sync(tracer, original_func)(*args, **kwargs)
81
+
82
+ setattr(client.messages, "create", dispatcher)
83
+
84
+
85
+ def _wrap_non_streaming_sync(
86
+ tracer: Tracer, original_func: Callable[..., Message]
87
+ ) -> Callable[..., Message]:
88
+ def pre_hook(ctx: Dict[str, Any], *args: Any, **kwargs: Any) -> None:
89
+ ctx["span"] = tracer.get_tracer().start_span(
90
+ "ANTHROPIC_API_CALL", attributes={AttributeKeys.JUDGMENT_SPAN_KIND: "llm"}
91
+ )
92
+ tracer._inject_judgment_context(ctx["span"])
93
+ set_span_attribute(
94
+ ctx["span"], AttributeKeys.GEN_AI_PROMPT, safe_serialize(kwargs)
95
+ )
96
+ ctx["model_name"] = kwargs.get("model", "")
97
+ set_span_attribute(
98
+ ctx["span"], AttributeKeys.JUDGMENT_LLM_MODEL_NAME, ctx["model_name"]
99
+ )
100
+
101
+ def post_hook(ctx: Dict[str, Any], result: Message) -> None:
102
+ span = ctx.get("span")
103
+ if not span:
104
+ return
105
+
106
+ set_span_attribute(
107
+ span, AttributeKeys.GEN_AI_COMPLETION, safe_serialize(result)
108
+ )
109
+
110
+ if result.usage:
111
+ prompt_tokens, completion_tokens, cache_read, cache_creation = (
112
+ _extract_anthropic_tokens(result.usage)
113
+ )
114
+ set_span_attribute(
115
+ span,
116
+ AttributeKeys.JUDGMENT_USAGE_NON_CACHED_INPUT_TOKENS,
117
+ prompt_tokens,
118
+ )
119
+ set_span_attribute(
120
+ span, AttributeKeys.JUDGMENT_USAGE_OUTPUT_TOKENS, completion_tokens
121
+ )
122
+ set_span_attribute(
123
+ span, AttributeKeys.JUDGMENT_USAGE_CACHE_READ_INPUT_TOKENS, cache_read
124
+ )
125
+ set_span_attribute(
126
+ span,
127
+ AttributeKeys.JUDGMENT_USAGE_CACHE_CREATION_INPUT_TOKENS,
128
+ cache_creation,
129
+ )
130
+ set_span_attribute(
131
+ span,
132
+ AttributeKeys.JUDGMENT_USAGE_METADATA,
133
+ safe_serialize(result.usage),
134
+ )
135
+
136
+ set_span_attribute(
137
+ span,
138
+ AttributeKeys.JUDGMENT_LLM_MODEL_NAME,
139
+ result.model,
140
+ )
141
+
142
+ def error_hook(ctx: Dict[str, Any], error: Exception) -> None:
143
+ span = ctx.get("span")
144
+ if span:
145
+ span.record_exception(error)
146
+
147
+ def finally_hook(ctx: Dict[str, Any]) -> None:
148
+ span = ctx.get("span")
149
+ if span:
150
+ span.end()
151
+
152
+ return immutable_wrap_sync(
153
+ original_func,
154
+ pre_hook=pre_hook,
155
+ post_hook=post_hook,
156
+ error_hook=error_hook,
157
+ finally_hook=finally_hook,
158
+ )
159
+
160
+
161
+ def _wrap_streaming_sync(
162
+ tracer: Tracer, original_func: Callable[..., Iterator[RawMessageStreamEvent]]
163
+ ) -> Callable[..., Iterator[RawMessageStreamEvent]]:
164
+ def pre_hook(ctx: Dict[str, Any], *args: Any, **kwargs: Any) -> None:
165
+ ctx["span"] = tracer.get_tracer().start_span(
166
+ "ANTHROPIC_API_CALL", attributes={AttributeKeys.JUDGMENT_SPAN_KIND: "llm"}
167
+ )
168
+ tracer._inject_judgment_context(ctx["span"])
169
+ set_span_attribute(
170
+ ctx["span"], AttributeKeys.GEN_AI_PROMPT, safe_serialize(kwargs)
171
+ )
172
+ ctx["model_name"] = kwargs.get("model", "")
173
+ set_span_attribute(
174
+ ctx["span"], AttributeKeys.JUDGMENT_LLM_MODEL_NAME, ctx["model_name"]
175
+ )
176
+ ctx["accumulated_content"] = ""
177
+
178
+ def mutate_hook(
179
+ ctx: Dict[str, Any], result: Iterator[RawMessageStreamEvent]
180
+ ) -> Iterator[RawMessageStreamEvent]:
181
+ def traced_generator() -> Generator[RawMessageStreamEvent, None, None]:
182
+ for chunk in result:
183
+ yield chunk
184
+
185
+ def yield_hook(inner_ctx: Dict[str, Any], chunk: RawMessageStreamEvent) -> None:
186
+ span = ctx.get("span")
187
+ if not span:
188
+ return
189
+
190
+ content = _extract_anthropic_content(chunk)
191
+ if content:
192
+ ctx["accumulated_content"] = (
193
+ ctx.get("accumulated_content", "") + content
194
+ )
195
+
196
+ usage_data = _extract_anthropic_chunk_usage(chunk)
197
+ if usage_data:
198
+ prompt_tokens, completion_tokens, cache_read, cache_creation = (
199
+ _extract_anthropic_tokens(usage_data)
200
+ )
201
+ set_span_attribute(
202
+ span,
203
+ AttributeKeys.JUDGMENT_USAGE_NON_CACHED_INPUT_TOKENS,
204
+ prompt_tokens,
205
+ )
206
+ set_span_attribute(
207
+ span, AttributeKeys.JUDGMENT_USAGE_OUTPUT_TOKENS, completion_tokens
208
+ )
209
+ set_span_attribute(
210
+ span,
211
+ AttributeKeys.JUDGMENT_USAGE_CACHE_READ_INPUT_TOKENS,
212
+ cache_read,
213
+ )
214
+ set_span_attribute(
215
+ span,
216
+ AttributeKeys.JUDGMENT_USAGE_CACHE_CREATION_INPUT_TOKENS,
217
+ cache_creation,
218
+ )
219
+ set_span_attribute(
220
+ span,
221
+ AttributeKeys.JUDGMENT_USAGE_METADATA,
222
+ safe_serialize(usage_data),
223
+ )
224
+
225
+ def post_hook_inner(inner_ctx: Dict[str, Any]) -> None:
226
+ span = ctx.get("span")
227
+ if span:
228
+ accumulated = ctx.get("accumulated_content", "")
229
+ set_span_attribute(span, AttributeKeys.GEN_AI_COMPLETION, accumulated)
230
+
231
+ def error_hook_inner(inner_ctx: Dict[str, Any], error: Exception) -> None:
232
+ span = ctx.get("span")
233
+ if span:
234
+ span.record_exception(error)
235
+
236
+ def finally_hook_inner(inner_ctx: Dict[str, Any]) -> None:
237
+ span = ctx.get("span")
238
+ if span:
239
+ span.end()
240
+
241
+ wrapped_generator = immutable_wrap_sync_iterator(
242
+ traced_generator,
243
+ yield_hook=yield_hook,
244
+ post_hook=post_hook_inner,
245
+ error_hook=error_hook_inner,
246
+ finally_hook=finally_hook_inner,
247
+ )
248
+
249
+ return wrapped_generator()
250
+
251
+ def error_hook(ctx: Dict[str, Any], error: Exception) -> None:
252
+ span = ctx.get("span")
253
+ if span:
254
+ span.record_exception(error)
255
+
256
+ return mutable_wrap_sync(
257
+ original_func,
258
+ pre_hook=pre_hook,
259
+ mutate_hook=mutate_hook,
260
+ error_hook=error_hook,
261
+ )
262
+
263
+
264
+ def wrap_messages_create_async(tracer: Tracer, client: AsyncAnthropic) -> None:
265
+ original_func = client.messages.create
266
+
267
+ async def dispatcher(*args: Any, **kwargs: Any) -> Any:
268
+ if kwargs.get("stream", False):
269
+ return await _wrap_streaming_async(tracer, original_func)(*args, **kwargs)
270
+ return await _wrap_non_streaming_async(tracer, original_func)(*args, **kwargs)
271
+
272
+ setattr(client.messages, "create", dispatcher)
273
+
274
+
275
+ def _wrap_non_streaming_async(
276
+ tracer: Tracer, original_func: Callable[..., Awaitable[Message]]
277
+ ) -> Callable[..., Awaitable[Message]]:
278
+ def pre_hook(ctx: Dict[str, Any], *args: Any, **kwargs: Any) -> None:
279
+ ctx["span"] = tracer.get_tracer().start_span(
280
+ "ANTHROPIC_API_CALL", attributes={AttributeKeys.JUDGMENT_SPAN_KIND: "llm"}
281
+ )
282
+ tracer._inject_judgment_context(ctx["span"])
283
+ set_span_attribute(
284
+ ctx["span"], AttributeKeys.GEN_AI_PROMPT, safe_serialize(kwargs)
285
+ )
286
+ ctx["model_name"] = kwargs.get("model", "")
287
+ set_span_attribute(
288
+ ctx["span"], AttributeKeys.JUDGMENT_LLM_MODEL_NAME, ctx["model_name"]
289
+ )
290
+
291
+ def post_hook(ctx: Dict[str, Any], result: Message) -> None:
292
+ span = ctx.get("span")
293
+ if not span:
294
+ return
295
+
296
+ set_span_attribute(
297
+ span, AttributeKeys.GEN_AI_COMPLETION, safe_serialize(result)
298
+ )
299
+
300
+ if result.usage:
301
+ prompt_tokens, completion_tokens, cache_read, cache_creation = (
302
+ _extract_anthropic_tokens(result.usage)
303
+ )
304
+ set_span_attribute(
305
+ span,
306
+ AttributeKeys.JUDGMENT_USAGE_NON_CACHED_INPUT_TOKENS,
307
+ prompt_tokens,
308
+ )
309
+ set_span_attribute(
310
+ span, AttributeKeys.JUDGMENT_USAGE_OUTPUT_TOKENS, completion_tokens
311
+ )
312
+ set_span_attribute(
313
+ span, AttributeKeys.JUDGMENT_USAGE_CACHE_READ_INPUT_TOKENS, cache_read
314
+ )
315
+ set_span_attribute(
316
+ span,
317
+ AttributeKeys.JUDGMENT_USAGE_CACHE_CREATION_INPUT_TOKENS,
318
+ cache_creation,
319
+ )
320
+ set_span_attribute(
321
+ span,
322
+ AttributeKeys.JUDGMENT_USAGE_METADATA,
323
+ safe_serialize(result.usage),
324
+ )
325
+
326
+ set_span_attribute(
327
+ span,
328
+ AttributeKeys.JUDGMENT_LLM_MODEL_NAME,
329
+ result.model,
330
+ )
331
+
332
+ def error_hook(ctx: Dict[str, Any], error: Exception) -> None:
333
+ span = ctx.get("span")
334
+ if span:
335
+ span.record_exception(error)
336
+
337
+ def finally_hook(ctx: Dict[str, Any]) -> None:
338
+ span = ctx.get("span")
339
+ if span:
340
+ span.end()
341
+
342
+ return immutable_wrap_async(
343
+ original_func,
344
+ pre_hook=pre_hook,
345
+ post_hook=post_hook,
346
+ error_hook=error_hook,
347
+ finally_hook=finally_hook,
348
+ )
349
+
350
+
351
+ def _wrap_streaming_async(
352
+ tracer: Tracer,
353
+ original_func: Callable[..., Awaitable[AsyncIterator[RawMessageStreamEvent]]],
354
+ ) -> Callable[..., Awaitable[AsyncIterator[RawMessageStreamEvent]]]:
355
+ def pre_hook(ctx: Dict[str, Any], *args: Any, **kwargs: Any) -> None:
356
+ ctx["span"] = tracer.get_tracer().start_span(
357
+ "ANTHROPIC_API_CALL", attributes={AttributeKeys.JUDGMENT_SPAN_KIND: "llm"}
358
+ )
359
+ tracer._inject_judgment_context(ctx["span"])
360
+ set_span_attribute(
361
+ ctx["span"], AttributeKeys.GEN_AI_PROMPT, safe_serialize(kwargs)
362
+ )
363
+ ctx["model_name"] = kwargs.get("model", "")
364
+ set_span_attribute(
365
+ ctx["span"], AttributeKeys.JUDGMENT_LLM_MODEL_NAME, ctx["model_name"]
366
+ )
367
+ ctx["accumulated_content"] = ""
368
+
369
+ def mutate_hook(
370
+ ctx: Dict[str, Any], result: AsyncIterator[RawMessageStreamEvent]
371
+ ) -> AsyncIterator[RawMessageStreamEvent]:
372
+ async def traced_generator() -> AsyncGenerator[RawMessageStreamEvent, None]:
373
+ async for chunk in result:
374
+ yield chunk
375
+
376
+ def yield_hook(inner_ctx: Dict[str, Any], chunk: RawMessageStreamEvent) -> None:
377
+ span = ctx.get("span")
378
+ if not span:
379
+ return
380
+
381
+ content = _extract_anthropic_content(chunk)
382
+ if content:
383
+ ctx["accumulated_content"] = (
384
+ ctx.get("accumulated_content", "") + content
385
+ )
386
+
387
+ usage_data = _extract_anthropic_chunk_usage(chunk)
388
+ if usage_data:
389
+ prompt_tokens, completion_tokens, cache_read, cache_creation = (
390
+ _extract_anthropic_tokens(usage_data)
391
+ )
392
+ set_span_attribute(
393
+ span,
394
+ AttributeKeys.JUDGMENT_USAGE_NON_CACHED_INPUT_TOKENS,
395
+ prompt_tokens,
396
+ )
397
+ set_span_attribute(
398
+ span, AttributeKeys.JUDGMENT_USAGE_OUTPUT_TOKENS, completion_tokens
399
+ )
400
+ set_span_attribute(
401
+ span,
402
+ AttributeKeys.JUDGMENT_USAGE_CACHE_READ_INPUT_TOKENS,
403
+ cache_read,
404
+ )
405
+ set_span_attribute(
406
+ span,
407
+ AttributeKeys.JUDGMENT_USAGE_CACHE_CREATION_INPUT_TOKENS,
408
+ cache_creation,
409
+ )
410
+ set_span_attribute(
411
+ span,
412
+ AttributeKeys.JUDGMENT_USAGE_METADATA,
413
+ safe_serialize(usage_data),
414
+ )
415
+
416
+ def post_hook_inner(inner_ctx: Dict[str, Any]) -> None:
417
+ span = ctx.get("span")
418
+ if span:
419
+ accumulated = ctx.get("accumulated_content", "")
420
+ set_span_attribute(span, AttributeKeys.GEN_AI_COMPLETION, accumulated)
421
+
422
+ def error_hook_inner(inner_ctx: Dict[str, Any], error: Exception) -> None:
423
+ span = ctx.get("span")
424
+ if span:
425
+ span.record_exception(error)
426
+
427
+ def finally_hook_inner(inner_ctx: Dict[str, Any]) -> None:
428
+ span = ctx.get("span")
429
+ if span:
430
+ span.end()
431
+
432
+ wrapped_generator = immutable_wrap_async_iterator(
433
+ traced_generator,
434
+ yield_hook=yield_hook,
435
+ post_hook=post_hook_inner,
436
+ error_hook=error_hook_inner,
437
+ finally_hook=finally_hook_inner,
438
+ )
439
+
440
+ return wrapped_generator()
441
+
442
+ def error_hook(ctx: Dict[str, Any], error: Exception) -> None:
443
+ span = ctx.get("span")
444
+ if span:
445
+ span.record_exception(error)
446
+
447
+ return mutable_wrap_async(
448
+ original_func,
449
+ pre_hook=pre_hook,
450
+ mutate_hook=mutate_hook,
451
+ error_hook=error_hook,
452
+ )