judgeval 0.1.0__py3-none-any.whl → 0.23.0__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.
Files changed (234) hide show
  1. judgeval/__init__.py +173 -10
  2. judgeval/api/__init__.py +523 -0
  3. judgeval/api/api_types.py +413 -0
  4. judgeval/cli.py +112 -0
  5. judgeval/constants.py +7 -30
  6. judgeval/data/__init__.py +1 -3
  7. judgeval/data/evaluation_run.py +125 -0
  8. judgeval/data/example.py +14 -40
  9. judgeval/data/judgment_types.py +396 -146
  10. judgeval/data/result.py +11 -18
  11. judgeval/data/scorer_data.py +3 -26
  12. judgeval/data/scripts/openapi_transform.py +5 -5
  13. judgeval/data/trace.py +115 -194
  14. judgeval/dataset/__init__.py +335 -0
  15. judgeval/env.py +55 -0
  16. judgeval/evaluation/__init__.py +346 -0
  17. judgeval/exceptions.py +28 -0
  18. judgeval/integrations/langgraph/__init__.py +13 -0
  19. judgeval/integrations/openlit/__init__.py +51 -0
  20. judgeval/judges/__init__.py +2 -2
  21. judgeval/judges/litellm_judge.py +77 -16
  22. judgeval/judges/together_judge.py +88 -17
  23. judgeval/judges/utils.py +7 -20
  24. judgeval/judgment_attribute_keys.py +55 -0
  25. judgeval/{common/logger.py → logger.py} +24 -8
  26. judgeval/prompt/__init__.py +330 -0
  27. judgeval/scorers/__init__.py +11 -11
  28. judgeval/scorers/agent_scorer.py +15 -19
  29. judgeval/scorers/api_scorer.py +21 -23
  30. judgeval/scorers/base_scorer.py +54 -36
  31. judgeval/scorers/example_scorer.py +1 -3
  32. judgeval/scorers/judgeval_scorers/api_scorers/__init__.py +2 -24
  33. judgeval/scorers/judgeval_scorers/api_scorers/answer_correctness.py +2 -10
  34. judgeval/scorers/judgeval_scorers/api_scorers/answer_relevancy.py +2 -2
  35. judgeval/scorers/judgeval_scorers/api_scorers/faithfulness.py +2 -10
  36. judgeval/scorers/judgeval_scorers/api_scorers/instruction_adherence.py +2 -14
  37. judgeval/scorers/judgeval_scorers/api_scorers/prompt_scorer.py +171 -59
  38. judgeval/scorers/score.py +64 -47
  39. judgeval/scorers/utils.py +2 -107
  40. judgeval/tracer/__init__.py +1111 -2
  41. judgeval/tracer/constants.py +1 -0
  42. judgeval/tracer/exporters/__init__.py +40 -0
  43. judgeval/tracer/exporters/s3.py +119 -0
  44. judgeval/tracer/exporters/store.py +59 -0
  45. judgeval/tracer/exporters/utils.py +32 -0
  46. judgeval/tracer/keys.py +63 -0
  47. judgeval/tracer/llm/__init__.py +7 -0
  48. judgeval/tracer/llm/config.py +78 -0
  49. judgeval/tracer/llm/constants.py +9 -0
  50. judgeval/tracer/llm/llm_anthropic/__init__.py +3 -0
  51. judgeval/tracer/llm/llm_anthropic/config.py +6 -0
  52. judgeval/tracer/llm/llm_anthropic/messages.py +452 -0
  53. judgeval/tracer/llm/llm_anthropic/messages_stream.py +322 -0
  54. judgeval/tracer/llm/llm_anthropic/wrapper.py +59 -0
  55. judgeval/tracer/llm/llm_google/__init__.py +3 -0
  56. judgeval/tracer/llm/llm_google/config.py +6 -0
  57. judgeval/tracer/llm/llm_google/generate_content.py +127 -0
  58. judgeval/tracer/llm/llm_google/wrapper.py +30 -0
  59. judgeval/tracer/llm/llm_openai/__init__.py +3 -0
  60. judgeval/tracer/llm/llm_openai/beta_chat_completions.py +216 -0
  61. judgeval/tracer/llm/llm_openai/chat_completions.py +501 -0
  62. judgeval/tracer/llm/llm_openai/config.py +6 -0
  63. judgeval/tracer/llm/llm_openai/responses.py +506 -0
  64. judgeval/tracer/llm/llm_openai/utils.py +42 -0
  65. judgeval/tracer/llm/llm_openai/wrapper.py +63 -0
  66. judgeval/tracer/llm/llm_together/__init__.py +3 -0
  67. judgeval/tracer/llm/llm_together/chat_completions.py +406 -0
  68. judgeval/tracer/llm/llm_together/config.py +6 -0
  69. judgeval/tracer/llm/llm_together/wrapper.py +52 -0
  70. judgeval/tracer/llm/providers.py +19 -0
  71. judgeval/tracer/managers.py +167 -0
  72. judgeval/tracer/processors/__init__.py +220 -0
  73. judgeval/tracer/utils.py +19 -0
  74. judgeval/trainer/__init__.py +14 -0
  75. judgeval/trainer/base_trainer.py +122 -0
  76. judgeval/trainer/config.py +123 -0
  77. judgeval/trainer/console.py +144 -0
  78. judgeval/trainer/fireworks_trainer.py +392 -0
  79. judgeval/trainer/trainable_model.py +252 -0
  80. judgeval/trainer/trainer.py +70 -0
  81. judgeval/utils/async_utils.py +39 -0
  82. judgeval/utils/decorators/__init__.py +0 -0
  83. judgeval/utils/decorators/dont_throw.py +37 -0
  84. judgeval/utils/decorators/use_once.py +13 -0
  85. judgeval/utils/file_utils.py +74 -28
  86. judgeval/utils/guards.py +36 -0
  87. judgeval/utils/meta.py +27 -0
  88. judgeval/utils/project.py +15 -0
  89. judgeval/utils/serialize.py +253 -0
  90. judgeval/utils/testing.py +70 -0
  91. judgeval/utils/url.py +10 -0
  92. judgeval/{version_check.py → utils/version_check.py} +5 -3
  93. judgeval/utils/wrappers/README.md +3 -0
  94. judgeval/utils/wrappers/__init__.py +15 -0
  95. judgeval/utils/wrappers/immutable_wrap_async.py +74 -0
  96. judgeval/utils/wrappers/immutable_wrap_async_iterator.py +84 -0
  97. judgeval/utils/wrappers/immutable_wrap_sync.py +66 -0
  98. judgeval/utils/wrappers/immutable_wrap_sync_iterator.py +84 -0
  99. judgeval/utils/wrappers/mutable_wrap_async.py +67 -0
  100. judgeval/utils/wrappers/mutable_wrap_sync.py +67 -0
  101. judgeval/utils/wrappers/py.typed +0 -0
  102. judgeval/utils/wrappers/utils.py +35 -0
  103. judgeval/v1/__init__.py +88 -0
  104. judgeval/v1/data/__init__.py +7 -0
  105. judgeval/v1/data/example.py +44 -0
  106. judgeval/v1/data/scorer_data.py +42 -0
  107. judgeval/v1/data/scoring_result.py +44 -0
  108. judgeval/v1/datasets/__init__.py +6 -0
  109. judgeval/v1/datasets/dataset.py +214 -0
  110. judgeval/v1/datasets/dataset_factory.py +94 -0
  111. judgeval/v1/evaluation/__init__.py +6 -0
  112. judgeval/v1/evaluation/evaluation.py +182 -0
  113. judgeval/v1/evaluation/evaluation_factory.py +17 -0
  114. judgeval/v1/instrumentation/__init__.py +6 -0
  115. judgeval/v1/instrumentation/llm/__init__.py +7 -0
  116. judgeval/v1/instrumentation/llm/config.py +78 -0
  117. judgeval/v1/instrumentation/llm/constants.py +11 -0
  118. judgeval/v1/instrumentation/llm/llm_anthropic/__init__.py +5 -0
  119. judgeval/v1/instrumentation/llm/llm_anthropic/config.py +6 -0
  120. judgeval/v1/instrumentation/llm/llm_anthropic/messages.py +414 -0
  121. judgeval/v1/instrumentation/llm/llm_anthropic/messages_stream.py +307 -0
  122. judgeval/v1/instrumentation/llm/llm_anthropic/wrapper.py +61 -0
  123. judgeval/v1/instrumentation/llm/llm_google/__init__.py +5 -0
  124. judgeval/v1/instrumentation/llm/llm_google/config.py +6 -0
  125. judgeval/v1/instrumentation/llm/llm_google/generate_content.py +121 -0
  126. judgeval/v1/instrumentation/llm/llm_google/wrapper.py +30 -0
  127. judgeval/v1/instrumentation/llm/llm_openai/__init__.py +5 -0
  128. judgeval/v1/instrumentation/llm/llm_openai/beta_chat_completions.py +212 -0
  129. judgeval/v1/instrumentation/llm/llm_openai/chat_completions.py +477 -0
  130. judgeval/v1/instrumentation/llm/llm_openai/config.py +6 -0
  131. judgeval/v1/instrumentation/llm/llm_openai/responses.py +472 -0
  132. judgeval/v1/instrumentation/llm/llm_openai/utils.py +41 -0
  133. judgeval/v1/instrumentation/llm/llm_openai/wrapper.py +63 -0
  134. judgeval/v1/instrumentation/llm/llm_together/__init__.py +5 -0
  135. judgeval/v1/instrumentation/llm/llm_together/chat_completions.py +382 -0
  136. judgeval/v1/instrumentation/llm/llm_together/config.py +6 -0
  137. judgeval/v1/instrumentation/llm/llm_together/wrapper.py +57 -0
  138. judgeval/v1/instrumentation/llm/providers.py +19 -0
  139. judgeval/v1/integrations/claude_agent_sdk/__init__.py +119 -0
  140. judgeval/v1/integrations/claude_agent_sdk/wrapper.py +564 -0
  141. judgeval/v1/integrations/langgraph/__init__.py +13 -0
  142. judgeval/v1/integrations/openlit/__init__.py +47 -0
  143. judgeval/v1/internal/api/__init__.py +525 -0
  144. judgeval/v1/internal/api/api_types.py +413 -0
  145. judgeval/v1/prompts/__init__.py +6 -0
  146. judgeval/v1/prompts/prompt.py +29 -0
  147. judgeval/v1/prompts/prompt_factory.py +189 -0
  148. judgeval/v1/py.typed +0 -0
  149. judgeval/v1/scorers/__init__.py +6 -0
  150. judgeval/v1/scorers/api_scorer.py +82 -0
  151. judgeval/v1/scorers/base_scorer.py +17 -0
  152. judgeval/v1/scorers/built_in/__init__.py +17 -0
  153. judgeval/v1/scorers/built_in/answer_correctness.py +28 -0
  154. judgeval/v1/scorers/built_in/answer_relevancy.py +28 -0
  155. judgeval/v1/scorers/built_in/built_in_factory.py +26 -0
  156. judgeval/v1/scorers/built_in/faithfulness.py +28 -0
  157. judgeval/v1/scorers/built_in/instruction_adherence.py +28 -0
  158. judgeval/v1/scorers/custom_scorer/__init__.py +6 -0
  159. judgeval/v1/scorers/custom_scorer/custom_scorer.py +50 -0
  160. judgeval/v1/scorers/custom_scorer/custom_scorer_factory.py +16 -0
  161. judgeval/v1/scorers/prompt_scorer/__init__.py +6 -0
  162. judgeval/v1/scorers/prompt_scorer/prompt_scorer.py +86 -0
  163. judgeval/v1/scorers/prompt_scorer/prompt_scorer_factory.py +85 -0
  164. judgeval/v1/scorers/scorers_factory.py +49 -0
  165. judgeval/v1/tracer/__init__.py +7 -0
  166. judgeval/v1/tracer/base_tracer.py +520 -0
  167. judgeval/v1/tracer/exporters/__init__.py +14 -0
  168. judgeval/v1/tracer/exporters/in_memory_span_exporter.py +25 -0
  169. judgeval/v1/tracer/exporters/judgment_span_exporter.py +42 -0
  170. judgeval/v1/tracer/exporters/noop_span_exporter.py +19 -0
  171. judgeval/v1/tracer/exporters/span_store.py +50 -0
  172. judgeval/v1/tracer/judgment_tracer_provider.py +70 -0
  173. judgeval/v1/tracer/processors/__init__.py +6 -0
  174. judgeval/v1/tracer/processors/_lifecycles/__init__.py +28 -0
  175. judgeval/v1/tracer/processors/_lifecycles/agent_id_processor.py +53 -0
  176. judgeval/v1/tracer/processors/_lifecycles/context_keys.py +11 -0
  177. judgeval/v1/tracer/processors/_lifecycles/customer_id_processor.py +29 -0
  178. judgeval/v1/tracer/processors/_lifecycles/registry.py +18 -0
  179. judgeval/v1/tracer/processors/judgment_span_processor.py +165 -0
  180. judgeval/v1/tracer/processors/noop_span_processor.py +42 -0
  181. judgeval/v1/tracer/tracer.py +67 -0
  182. judgeval/v1/tracer/tracer_factory.py +38 -0
  183. judgeval/v1/trainers/__init__.py +5 -0
  184. judgeval/v1/trainers/base_trainer.py +62 -0
  185. judgeval/v1/trainers/config.py +123 -0
  186. judgeval/v1/trainers/console.py +144 -0
  187. judgeval/v1/trainers/fireworks_trainer.py +392 -0
  188. judgeval/v1/trainers/trainable_model.py +252 -0
  189. judgeval/v1/trainers/trainers_factory.py +37 -0
  190. judgeval/v1/utils.py +18 -0
  191. judgeval/version.py +5 -0
  192. judgeval/warnings.py +4 -0
  193. judgeval-0.23.0.dist-info/METADATA +266 -0
  194. judgeval-0.23.0.dist-info/RECORD +201 -0
  195. judgeval-0.23.0.dist-info/entry_points.txt +2 -0
  196. judgeval/clients.py +0 -34
  197. judgeval/common/__init__.py +0 -13
  198. judgeval/common/api/__init__.py +0 -3
  199. judgeval/common/api/api.py +0 -352
  200. judgeval/common/api/constants.py +0 -165
  201. judgeval/common/exceptions.py +0 -27
  202. judgeval/common/storage/__init__.py +0 -6
  203. judgeval/common/storage/s3_storage.py +0 -98
  204. judgeval/common/tracer/__init__.py +0 -31
  205. judgeval/common/tracer/constants.py +0 -22
  206. judgeval/common/tracer/core.py +0 -1916
  207. judgeval/common/tracer/otel_exporter.py +0 -108
  208. judgeval/common/tracer/otel_span_processor.py +0 -234
  209. judgeval/common/tracer/span_processor.py +0 -37
  210. judgeval/common/tracer/span_transformer.py +0 -211
  211. judgeval/common/tracer/trace_manager.py +0 -92
  212. judgeval/common/utils.py +0 -940
  213. judgeval/data/datasets/__init__.py +0 -4
  214. judgeval/data/datasets/dataset.py +0 -341
  215. judgeval/data/datasets/eval_dataset_client.py +0 -214
  216. judgeval/data/tool.py +0 -5
  217. judgeval/data/trace_run.py +0 -37
  218. judgeval/evaluation_run.py +0 -75
  219. judgeval/integrations/langgraph.py +0 -843
  220. judgeval/judges/mixture_of_judges.py +0 -286
  221. judgeval/judgment_client.py +0 -369
  222. judgeval/rules.py +0 -521
  223. judgeval/run_evaluation.py +0 -684
  224. judgeval/scorers/judgeval_scorers/api_scorers/derailment_scorer.py +0 -14
  225. judgeval/scorers/judgeval_scorers/api_scorers/execution_order.py +0 -52
  226. judgeval/scorers/judgeval_scorers/api_scorers/hallucination.py +0 -28
  227. judgeval/scorers/judgeval_scorers/api_scorers/tool_dependency.py +0 -20
  228. judgeval/scorers/judgeval_scorers/api_scorers/tool_order.py +0 -27
  229. judgeval/utils/alerts.py +0 -93
  230. judgeval/utils/requests.py +0 -50
  231. judgeval-0.1.0.dist-info/METADATA +0 -202
  232. judgeval-0.1.0.dist-info/RECORD +0 -73
  233. {judgeval-0.1.0.dist-info → judgeval-0.23.0.dist-info}/WHEEL +0 -0
  234. {judgeval-0.1.0.dist-info → judgeval-0.23.0.dist-info}/licenses/LICENSE.md +0 -0
@@ -0,0 +1,472 @@
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
+ ParamSpec,
13
+ TypeVar,
14
+ )
15
+
16
+ from opentelemetry.trace import Status, StatusCode
17
+ from judgeval.judgment_attribute_keys import AttributeKeys
18
+ from judgeval.utils.serialize import safe_serialize
19
+ from judgeval.utils.wrappers import (
20
+ immutable_wrap_sync,
21
+ immutable_wrap_async,
22
+ mutable_wrap_sync,
23
+ mutable_wrap_async,
24
+ immutable_wrap_sync_iterator,
25
+ immutable_wrap_async_iterator,
26
+ )
27
+ from judgeval.v1.instrumentation.llm.llm_openai.utils import (
28
+ openai_tokens_converter,
29
+ set_cost_attribute,
30
+ )
31
+
32
+ if TYPE_CHECKING:
33
+ from judgeval.v1.tracer import BaseTracer
34
+ from openai import OpenAI, AsyncOpenAI
35
+ from openai.types.responses import Response
36
+
37
+ P = ParamSpec("P")
38
+ T = TypeVar("T")
39
+
40
+
41
+ def wrap_responses_create_sync(tracer: BaseTracer, client: OpenAI) -> None:
42
+ original_func = client.responses.create
43
+
44
+ def dispatcher(*args: Any, **kwargs: Any) -> Any:
45
+ if kwargs.get("stream", False):
46
+ return _wrap_responses_streaming_sync(tracer, original_func)(
47
+ *args, **kwargs
48
+ )
49
+ return _wrap_responses_non_streaming_sync(tracer, original_func)(
50
+ *args, **kwargs
51
+ )
52
+
53
+ setattr(client.responses, "create", dispatcher)
54
+
55
+
56
+ def _wrap_responses_non_streaming_sync(
57
+ tracer: BaseTracer, original_func: Callable[..., Response]
58
+ ) -> Callable[..., Response]:
59
+ def pre_hook(ctx: Dict[str, Any], *args: Any, **kwargs: Any) -> None:
60
+ ctx["span"] = tracer.get_tracer().start_span(
61
+ "OPENAI_API_CALL", attributes={AttributeKeys.JUDGMENT_SPAN_KIND: "llm"}
62
+ )
63
+ ctx["span"].set_attribute(AttributeKeys.GEN_AI_PROMPT, safe_serialize(kwargs))
64
+ ctx["model_name"] = kwargs.get("model", "")
65
+ ctx["span"].set_attribute(
66
+ AttributeKeys.JUDGMENT_LLM_MODEL_NAME, ctx["model_name"]
67
+ )
68
+
69
+ def post_hook(ctx: Dict[str, Any], result: Response) -> None:
70
+ span = ctx.get("span")
71
+ if not span:
72
+ return
73
+
74
+ span.set_attribute(AttributeKeys.GEN_AI_COMPLETION, safe_serialize(result))
75
+
76
+ usage_data = result.usage if hasattr(result, "usage") else None
77
+ if usage_data:
78
+ prompt_tokens = usage_data.input_tokens or 0
79
+ completion_tokens = usage_data.output_tokens or 0
80
+ cache_read = usage_data.input_tokens_details.cached_tokens or 0
81
+
82
+ set_cost_attribute(span, usage_data)
83
+ prompt_tokens, completion_tokens, cache_read, cache_creation = (
84
+ openai_tokens_converter(
85
+ prompt_tokens,
86
+ completion_tokens,
87
+ cache_read,
88
+ 0,
89
+ usage_data.total_tokens,
90
+ )
91
+ )
92
+
93
+ span.set_attribute(
94
+ AttributeKeys.JUDGMENT_USAGE_NON_CACHED_INPUT_TOKENS,
95
+ prompt_tokens,
96
+ )
97
+ span.set_attribute(
98
+ AttributeKeys.JUDGMENT_USAGE_OUTPUT_TOKENS, completion_tokens
99
+ )
100
+ span.set_attribute(
101
+ AttributeKeys.JUDGMENT_USAGE_CACHE_READ_INPUT_TOKENS, cache_read
102
+ )
103
+ span.set_attribute(
104
+ AttributeKeys.JUDGMENT_USAGE_CACHE_CREATION_INPUT_TOKENS, 0
105
+ )
106
+ span.set_attribute(
107
+ AttributeKeys.JUDGMENT_USAGE_METADATA,
108
+ safe_serialize(usage_data),
109
+ )
110
+
111
+ if hasattr(result, "model"):
112
+ span.set_attribute(
113
+ AttributeKeys.JUDGMENT_LLM_MODEL_NAME,
114
+ result.model or ctx["model_name"],
115
+ )
116
+
117
+ def error_hook(ctx: Dict[str, Any], error: Exception) -> None:
118
+ span = ctx.get("span")
119
+ if span:
120
+ span.record_exception(error)
121
+ span.set_status(Status(StatusCode.ERROR))
122
+
123
+ def finally_hook(ctx: Dict[str, Any]) -> None:
124
+ span = ctx.get("span")
125
+ if span:
126
+ span.end()
127
+
128
+ return immutable_wrap_sync(
129
+ original_func,
130
+ pre_hook=pre_hook,
131
+ post_hook=post_hook,
132
+ error_hook=error_hook,
133
+ finally_hook=finally_hook,
134
+ )
135
+
136
+
137
+ def _wrap_responses_streaming_sync(
138
+ tracer: BaseTracer, original_func: Callable[..., Iterator[Any]]
139
+ ) -> Callable[..., Iterator[Any]]:
140
+ def pre_hook(ctx: Dict[str, Any], *args: Any, **kwargs: Any) -> None:
141
+ ctx["span"] = tracer.get_tracer().start_span(
142
+ "OPENAI_API_CALL", attributes={AttributeKeys.JUDGMENT_SPAN_KIND: "llm"}
143
+ )
144
+ ctx["span"].set_attribute(AttributeKeys.GEN_AI_PROMPT, safe_serialize(kwargs))
145
+ ctx["model_name"] = kwargs.get("model", "")
146
+ ctx["span"].set_attribute(
147
+ AttributeKeys.JUDGMENT_LLM_MODEL_NAME, ctx["model_name"]
148
+ )
149
+ ctx["accumulated_content"] = ""
150
+
151
+ def mutate_hook(ctx: Dict[str, Any], result: Iterator[Any]) -> Iterator[Any]:
152
+ def traced_generator() -> Generator[Any, None, None]:
153
+ for chunk in result:
154
+ yield chunk
155
+
156
+ def yield_hook(inner_ctx: Dict[str, Any], chunk: Any) -> None:
157
+ span = ctx.get("span")
158
+ if not span:
159
+ return
160
+
161
+ if hasattr(chunk, "type") and chunk.type == "response.output_text.delta":
162
+ delta = getattr(chunk, "delta", None)
163
+ if delta:
164
+ ctx["accumulated_content"] = (
165
+ ctx.get("accumulated_content", "") + delta
166
+ )
167
+
168
+ if hasattr(chunk, "type") and chunk.type == "response.completed":
169
+ if (
170
+ hasattr(chunk, "response")
171
+ and chunk.response
172
+ and hasattr(chunk.response, "usage")
173
+ and chunk.response.usage
174
+ ):
175
+ prompt_tokens = chunk.response.usage.input_tokens or 0
176
+ completion_tokens = chunk.response.usage.output_tokens or 0
177
+ # Safely access nested cached_tokens
178
+ input_tokens_details = getattr(
179
+ chunk.response.usage, "input_tokens_details", None
180
+ )
181
+ cache_read = (
182
+ getattr(input_tokens_details, "cached_tokens", 0)
183
+ if input_tokens_details
184
+ else 0
185
+ )
186
+
187
+ set_cost_attribute(span, chunk.response.usage)
188
+ prompt_tokens, completion_tokens, cache_read, cache_creation = (
189
+ openai_tokens_converter(
190
+ prompt_tokens,
191
+ completion_tokens,
192
+ cache_read,
193
+ 0,
194
+ chunk.response.usage.total_tokens,
195
+ )
196
+ )
197
+
198
+ span.set_attribute(
199
+ AttributeKeys.JUDGMENT_USAGE_NON_CACHED_INPUT_TOKENS,
200
+ prompt_tokens,
201
+ )
202
+ span.set_attribute(
203
+ AttributeKeys.JUDGMENT_USAGE_OUTPUT_TOKENS, completion_tokens
204
+ )
205
+ span.set_attribute(
206
+ AttributeKeys.JUDGMENT_USAGE_CACHE_READ_INPUT_TOKENS, cache_read
207
+ )
208
+ span.set_attribute(
209
+ AttributeKeys.JUDGMENT_USAGE_CACHE_CREATION_INPUT_TOKENS, 0
210
+ )
211
+ span.set_attribute(
212
+ AttributeKeys.JUDGMENT_USAGE_METADATA,
213
+ safe_serialize(chunk.response.usage),
214
+ )
215
+
216
+ def post_hook_inner(inner_ctx: Dict[str, Any]) -> None:
217
+ span = ctx.get("span")
218
+ if span:
219
+ accumulated = ctx.get("accumulated_content", "")
220
+ span.set_attribute(AttributeKeys.GEN_AI_COMPLETION, accumulated)
221
+
222
+ def error_hook_inner(inner_ctx: Dict[str, Any], error: Exception) -> None:
223
+ span = ctx.get("span")
224
+ if span:
225
+ span.record_exception(error)
226
+ span.set_status(Status(StatusCode.ERROR))
227
+
228
+ def finally_hook_inner(inner_ctx: Dict[str, Any]) -> None:
229
+ span = ctx.get("span")
230
+ if span:
231
+ span.end()
232
+
233
+ wrapped_generator = immutable_wrap_sync_iterator(
234
+ traced_generator,
235
+ yield_hook=yield_hook,
236
+ post_hook=post_hook_inner,
237
+ error_hook=error_hook_inner,
238
+ finally_hook=finally_hook_inner,
239
+ )
240
+
241
+ return wrapped_generator()
242
+
243
+ def error_hook(ctx: Dict[str, Any], error: Exception) -> None:
244
+ span = ctx.get("span")
245
+ if span:
246
+ span.record_exception(error)
247
+ span.set_status(Status(StatusCode.ERROR))
248
+
249
+ return mutable_wrap_sync(
250
+ original_func,
251
+ pre_hook=pre_hook,
252
+ mutate_hook=mutate_hook,
253
+ error_hook=error_hook,
254
+ )
255
+
256
+
257
+ def wrap_responses_create_async(tracer: BaseTracer, client: AsyncOpenAI) -> None:
258
+ original_func = client.responses.create
259
+
260
+ async def dispatcher(*args: Any, **kwargs: Any) -> Any:
261
+ if kwargs.get("stream", False):
262
+ return await _wrap_responses_streaming_async(tracer, original_func)(
263
+ *args, **kwargs
264
+ )
265
+ return await _wrap_responses_non_streaming_async(tracer, original_func)(
266
+ *args, **kwargs
267
+ )
268
+
269
+ setattr(client.responses, "create", dispatcher)
270
+
271
+
272
+ def _wrap_responses_non_streaming_async(
273
+ tracer: BaseTracer, original_func: Callable[..., Awaitable[Response]]
274
+ ) -> Callable[..., Awaitable[Response]]:
275
+ def pre_hook(ctx: Dict[str, Any], *args: Any, **kwargs: Any) -> None:
276
+ ctx["span"] = tracer.get_tracer().start_span(
277
+ "OPENAI_API_CALL", attributes={AttributeKeys.JUDGMENT_SPAN_KIND: "llm"}
278
+ )
279
+ ctx["span"].set_attribute(AttributeKeys.GEN_AI_PROMPT, safe_serialize(kwargs))
280
+ ctx["model_name"] = kwargs.get("model", "")
281
+ ctx["span"].set_attribute(
282
+ AttributeKeys.JUDGMENT_LLM_MODEL_NAME, ctx["model_name"]
283
+ )
284
+
285
+ def post_hook(ctx: Dict[str, Any], result: Response) -> None:
286
+ span = ctx.get("span")
287
+ if not span:
288
+ return
289
+
290
+ span.set_attribute(AttributeKeys.GEN_AI_COMPLETION, safe_serialize(result))
291
+
292
+ usage_data = result.usage if hasattr(result, "usage") else None
293
+ if usage_data:
294
+ prompt_tokens = usage_data.input_tokens or 0
295
+ completion_tokens = usage_data.output_tokens or 0
296
+ cache_read = usage_data.input_tokens_details.cached_tokens or 0
297
+
298
+ set_cost_attribute(span, usage_data)
299
+ prompt_tokens, completion_tokens, cache_read, cache_creation = (
300
+ openai_tokens_converter(
301
+ prompt_tokens,
302
+ completion_tokens,
303
+ cache_read,
304
+ 0,
305
+ usage_data.total_tokens,
306
+ )
307
+ )
308
+
309
+ span.set_attribute(
310
+ AttributeKeys.JUDGMENT_USAGE_NON_CACHED_INPUT_TOKENS,
311
+ prompt_tokens,
312
+ )
313
+ span.set_attribute(
314
+ AttributeKeys.JUDGMENT_USAGE_OUTPUT_TOKENS, completion_tokens
315
+ )
316
+ span.set_attribute(
317
+ AttributeKeys.JUDGMENT_USAGE_CACHE_READ_INPUT_TOKENS, cache_read
318
+ )
319
+ span.set_attribute(
320
+ AttributeKeys.JUDGMENT_USAGE_CACHE_CREATION_INPUT_TOKENS, 0
321
+ )
322
+ span.set_attribute(
323
+ AttributeKeys.JUDGMENT_USAGE_METADATA,
324
+ safe_serialize(usage_data),
325
+ )
326
+
327
+ if hasattr(result, "model"):
328
+ span.set_attribute(
329
+ AttributeKeys.JUDGMENT_LLM_MODEL_NAME,
330
+ result.model or ctx["model_name"],
331
+ )
332
+
333
+ def error_hook(ctx: Dict[str, Any], error: Exception) -> None:
334
+ span = ctx.get("span")
335
+ if span:
336
+ span.record_exception(error)
337
+ span.set_status(Status(StatusCode.ERROR))
338
+
339
+ def finally_hook(ctx: Dict[str, Any]) -> None:
340
+ span = ctx.get("span")
341
+ if span:
342
+ span.end()
343
+
344
+ return immutable_wrap_async(
345
+ original_func,
346
+ pre_hook=pre_hook,
347
+ post_hook=post_hook,
348
+ error_hook=error_hook,
349
+ finally_hook=finally_hook,
350
+ )
351
+
352
+
353
+ def _wrap_responses_streaming_async(
354
+ tracer: BaseTracer, original_func: Callable[..., Awaitable[AsyncIterator[Any]]]
355
+ ) -> Callable[..., Awaitable[AsyncIterator[Any]]]:
356
+ def pre_hook(ctx: Dict[str, Any], *args: Any, **kwargs: Any) -> None:
357
+ ctx["span"] = tracer.get_tracer().start_span(
358
+ "OPENAI_API_CALL", attributes={AttributeKeys.JUDGMENT_SPAN_KIND: "llm"}
359
+ )
360
+ ctx["span"].set_attribute(AttributeKeys.GEN_AI_PROMPT, safe_serialize(kwargs))
361
+ ctx["model_name"] = kwargs.get("model", "")
362
+ ctx["span"].set_attribute(
363
+ AttributeKeys.JUDGMENT_LLM_MODEL_NAME, ctx["model_name"]
364
+ )
365
+ ctx["accumulated_content"] = ""
366
+
367
+ def mutate_hook(
368
+ ctx: Dict[str, Any], result: AsyncIterator[Any]
369
+ ) -> AsyncIterator[Any]:
370
+ async def traced_generator() -> AsyncGenerator[Any, None]:
371
+ async for chunk in result:
372
+ yield chunk
373
+
374
+ def yield_hook(inner_ctx: Dict[str, Any], chunk: Any) -> None:
375
+ span = ctx.get("span")
376
+ if not span:
377
+ return
378
+
379
+ if hasattr(chunk, "type") and chunk.type == "response.output_text.delta":
380
+ delta = getattr(chunk, "delta", None)
381
+ if delta:
382
+ ctx["accumulated_content"] = (
383
+ ctx.get("accumulated_content", "") + delta
384
+ )
385
+
386
+ if hasattr(chunk, "type") and chunk.type == "response.completed":
387
+ if (
388
+ hasattr(chunk, "response")
389
+ and chunk.response
390
+ and hasattr(chunk.response, "usage")
391
+ and chunk.response.usage
392
+ ):
393
+ prompt_tokens = chunk.response.usage.input_tokens or 0
394
+ completion_tokens = chunk.response.usage.output_tokens or 0
395
+ # Safely access nested cached_tokens
396
+ input_tokens_details = getattr(
397
+ chunk.response.usage, "input_tokens_details", None
398
+ )
399
+ cache_read = (
400
+ getattr(input_tokens_details, "cached_tokens", 0)
401
+ if input_tokens_details
402
+ else 0
403
+ )
404
+
405
+ set_cost_attribute(span, chunk.response.usage)
406
+ prompt_tokens, completion_tokens, cache_read, cache_creation = (
407
+ openai_tokens_converter(
408
+ prompt_tokens,
409
+ completion_tokens,
410
+ cache_read,
411
+ 0,
412
+ chunk.response.usage.total_tokens,
413
+ )
414
+ )
415
+
416
+ span.set_attribute(
417
+ AttributeKeys.JUDGMENT_USAGE_NON_CACHED_INPUT_TOKENS,
418
+ prompt_tokens,
419
+ )
420
+ span.set_attribute(
421
+ AttributeKeys.JUDGMENT_USAGE_OUTPUT_TOKENS, completion_tokens
422
+ )
423
+ span.set_attribute(
424
+ AttributeKeys.JUDGMENT_USAGE_CACHE_READ_INPUT_TOKENS, cache_read
425
+ )
426
+ span.set_attribute(
427
+ AttributeKeys.JUDGMENT_USAGE_CACHE_CREATION_INPUT_TOKENS, 0
428
+ )
429
+ span.set_attribute(
430
+ AttributeKeys.JUDGMENT_USAGE_METADATA,
431
+ safe_serialize(chunk.response.usage),
432
+ )
433
+
434
+ def post_hook_inner(inner_ctx: Dict[str, Any]) -> None:
435
+ span = ctx.get("span")
436
+ if span:
437
+ accumulated = ctx.get("accumulated_content", "")
438
+ span.set_attribute(AttributeKeys.GEN_AI_COMPLETION, accumulated)
439
+
440
+ def error_hook_inner(inner_ctx: Dict[str, Any], error: Exception) -> None:
441
+ span = ctx.get("span")
442
+ if span:
443
+ span.record_exception(error)
444
+ span.set_status(Status(StatusCode.ERROR))
445
+
446
+ def finally_hook_inner(inner_ctx: Dict[str, Any]) -> None:
447
+ span = ctx.get("span")
448
+ if span:
449
+ span.end()
450
+
451
+ wrapped_generator = immutable_wrap_async_iterator(
452
+ traced_generator,
453
+ yield_hook=yield_hook,
454
+ post_hook=post_hook_inner,
455
+ error_hook=error_hook_inner,
456
+ finally_hook=finally_hook_inner,
457
+ )
458
+
459
+ return wrapped_generator()
460
+
461
+ def error_hook(ctx: Dict[str, Any], error: Exception) -> None:
462
+ span = ctx.get("span")
463
+ if span:
464
+ span.record_exception(error)
465
+ span.set_status(Status(StatusCode.ERROR))
466
+
467
+ return mutable_wrap_async(
468
+ original_func,
469
+ pre_hook=pre_hook,
470
+ mutate_hook=mutate_hook,
471
+ error_hook=error_hook,
472
+ )
@@ -0,0 +1,41 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Any
4
+ from opentelemetry.trace import Span
5
+ from judgeval.judgment_attribute_keys import AttributeKeys
6
+ from judgeval.utils.serialize import safe_serialize
7
+
8
+
9
+ def openai_tokens_converter(
10
+ prompt_tokens: int,
11
+ completion_tokens: int,
12
+ cache_read: int,
13
+ cache_creation: int,
14
+ total_tokens: int,
15
+ ) -> tuple[int, int, int, int]:
16
+ """
17
+ Returns:
18
+ tuple[int, int, int, int]:
19
+ - judgment.usage.non_cached_input
20
+ - judgment.usage.output_tokens
21
+ - judgment.usage.cached_input_tokens
22
+ - judgment.usage.cache_creation_tokens
23
+ """
24
+ manual_tokens = prompt_tokens + completion_tokens + cache_read + cache_creation
25
+
26
+ if manual_tokens > total_tokens:
27
+ return prompt_tokens - cache_read, completion_tokens, cache_read, cache_creation
28
+ else:
29
+ return prompt_tokens, completion_tokens, cache_read, cache_creation
30
+
31
+
32
+ def set_cost_attribute(span: Span, usage_data: Any) -> None:
33
+ """
34
+ This is for OpenRouter case where the cost is provided in the usage data when they specify:
35
+ extra_body={"usage": {"include": True}},
36
+ """
37
+ if hasattr(usage_data, "cost") and usage_data.cost:
38
+ span.set_attribute(
39
+ AttributeKeys.JUDGMENT_USAGE_TOTAL_COST_USD,
40
+ safe_serialize(usage_data.cost),
41
+ )
@@ -0,0 +1,63 @@
1
+ from __future__ import annotations
2
+ from typing import TYPE_CHECKING, Union
3
+ import typing
4
+
5
+ from judgeval.v1.instrumentation.llm.llm_openai.chat_completions import (
6
+ wrap_chat_completions_create_sync,
7
+ wrap_chat_completions_create_async,
8
+ )
9
+ from judgeval.v1.instrumentation.llm.llm_openai.responses import (
10
+ wrap_responses_create_sync,
11
+ wrap_responses_create_async,
12
+ )
13
+ from judgeval.v1.instrumentation.llm.llm_openai.beta_chat_completions import (
14
+ wrap_beta_chat_completions_parse_sync,
15
+ wrap_beta_chat_completions_parse_async,
16
+ )
17
+
18
+ if TYPE_CHECKING:
19
+ from judgeval.v1.tracer import BaseTracer
20
+ from openai import OpenAI, AsyncOpenAI
21
+
22
+ TClient = Union[OpenAI, AsyncOpenAI]
23
+
24
+
25
+ def wrap_openai_client_sync(tracer: BaseTracer, client: OpenAI) -> OpenAI:
26
+ wrap_chat_completions_create_sync(tracer, client)
27
+ wrap_responses_create_sync(tracer, client)
28
+ wrap_beta_chat_completions_parse_sync(tracer, client)
29
+ return client
30
+
31
+
32
+ def wrap_openai_client_async(tracer: BaseTracer, client: AsyncOpenAI) -> AsyncOpenAI:
33
+ wrap_chat_completions_create_async(tracer, client)
34
+ wrap_responses_create_async(tracer, client)
35
+ wrap_beta_chat_completions_parse_async(tracer, client)
36
+ return client
37
+
38
+
39
+ @typing.overload
40
+ def wrap_openai_client(tracer: BaseTracer, client: OpenAI) -> OpenAI: ...
41
+ @typing.overload
42
+ def wrap_openai_client(tracer: BaseTracer, client: AsyncOpenAI) -> AsyncOpenAI: ...
43
+
44
+
45
+ def wrap_openai_client(tracer: BaseTracer, client: TClient) -> TClient:
46
+ from judgeval.v1.instrumentation.llm.llm_openai.config import HAS_OPENAI
47
+ from judgeval.logger import judgeval_logger
48
+
49
+ if not HAS_OPENAI:
50
+ judgeval_logger.error(
51
+ "Cannot wrap OpenAI client: 'openai' library not installed. "
52
+ "Install it with: pip install openai"
53
+ )
54
+ return client
55
+
56
+ from openai import OpenAI, AsyncOpenAI
57
+
58
+ if isinstance(client, AsyncOpenAI):
59
+ return wrap_openai_client_async(tracer, client)
60
+ elif isinstance(client, OpenAI):
61
+ return wrap_openai_client_sync(tracer, client)
62
+ else:
63
+ raise TypeError(f"Invalid client type: {type(client)}")
@@ -0,0 +1,5 @@
1
+ from __future__ import annotations
2
+
3
+ from .wrapper import wrap_together_client
4
+
5
+ __all__ = ["wrap_together_client"]