ragaai-catalyst 2.1.7.5b5__py3-none-any.whl → 2.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.
@@ -1,10 +1,13 @@
1
1
  import json
2
2
  import sys
3
+ import uuid
3
4
  from datetime import datetime
4
5
  from typing import final, List, Dict, Any, Optional
5
6
  import pytz
6
7
  import uuid
7
8
  from ragaai_catalyst.tracers.agentic_tracing.utils.llm_utils import calculate_llm_cost, get_model_cost
9
+ import logging
10
+ logger = logging.getLogger(__name__)
8
11
 
9
12
  def convert_time_format(original_time_str, target_timezone_str="Asia/Kolkata"):
10
13
  """
@@ -47,184 +50,24 @@ def get_ordered_family(parent_children_mapping: Dict[str, Any]) -> List[str]:
47
50
  ordering_function(None, ordered_family)
48
51
  return reversed(ordered_family)
49
52
 
50
- def get_spans(input_trace, custom_model_cost):
51
- span_map = {}
52
- parent_children_mapping = {}
53
- span_type_mapping={"AGENT":"agent","LLM":"llm","TOOL":"tool"}
54
- span_name_occurrence = {}
55
- for span in input_trace:
56
- final_span = {}
57
- span_type=span_type_mapping.get(span["attributes"]["openinference.span.kind"],"custom")
58
- span_id = span["context"]["span_id"]
59
- parent_id = span["parent_id"]
60
- final_span["id"] = span_id
61
- if span["name"] not in span_name_occurrence:
62
- span_name_occurrence[span['name']]=0
63
- else:
64
- span_name_occurrence[span['name']]+=1
65
- final_span["name"] = span["name"]+"."+str(span_name_occurrence[span['name']])
66
- final_span["hash_id"] = get_uuid(final_span["name"])
67
- final_span["source_hash_id"] = None
68
- final_span["type"] = span_type
69
- final_span["start_time"] = convert_time_format(span['start_time'])
70
- final_span["end_time"] = convert_time_format(span['end_time'])
71
- final_span["parent_id"] = parent_id
72
- final_span["extra_info"] = None
73
- '''Handle Error if any'''
74
- if span["status"]["status_code"].lower() == "error":
75
- final_span["error"] = span["status"]
76
- else:
77
- final_span["error"] = None
78
- # ToDo: Find final trace format for sending error description
79
- final_span["metrics"] = []
80
- final_span["feedback"] = None
81
- final_span["data"]={}
82
- final_span["info"]={}
83
- final_span["metrics"] =[]
84
- final_span["extra_info"]={}
85
- if span_type=="agent":
86
- if "input.value" in span["attributes"]:
87
- try:
88
- final_span["data"]["input"] = json.loads(span["attributes"]["input.value"])
89
- except Exception as e:
90
- final_span["data"]["input"] = span["attributes"]["input.value"]
91
- else:
92
- final_span["data"]["input"] = ""
93
- if "output.value" in span["attributes"]:
94
- try:
95
- final_span["data"]["output"] = json.loads(span["attributes"]["output.value"])
96
- except Exception as e:
97
- final_span["data"]["output"] = span["attributes"]["output.value"]
98
- else:
99
- final_span["data"]["output"] = ""
100
- final_span["data"]['children'] = []
53
+ def get_spans(input_trace):
54
+ data = input_trace.copy()
55
+ import uuid
56
+ from collections import defaultdict
101
57
 
102
- elif span_type=="tool":
103
- available_fields = list(span['attributes'].keys())
104
- tool_fields = [key for key in available_fields if 'tool' in key]
105
- if "input.value" in span["attributes"]:
106
- try:
107
- final_span["data"]["input"] = json.loads(span["attributes"]["input.value"])
108
- except Exception as e:
109
- final_span["data"]["input"] = span["attributes"]["input.value"]
110
- else:
111
- final_span["data"]["input"] = ""
112
- if "output.value" in span["attributes"]:
113
- try:
114
- final_span["data"]["output"] = json.loads(span["attributes"]["output.value"])
115
- except Exception as e:
116
- final_span["data"]["output"] = span["attributes"]["output.value"]
117
- else:
118
- final_span["data"]["output"] = ""
119
- input_data={}
120
- for key in tool_fields:
121
- input_data[key] = span['attributes'].get(key, None)
122
- final_span["info"].update(input_data)
123
-
124
- elif span_type=="llm":
125
- available_fields = list(span['attributes'].keys())
126
- input_fields = [key for key in available_fields if 'input' in key]
127
- input_data = {}
128
- for key in input_fields:
129
- if 'mime_type' not in key:
130
- try:
131
- input_data[key] = json.loads(span['attributes'][key])
132
- except json.JSONDecodeError as e:
133
- input_data[key] = span['attributes'].get(key, None)
134
- final_span["data"]["input"] = input_data
135
-
136
- output_fields = [key for key in available_fields if 'output' in key]
137
- output_data = {}
138
- output_data['content'] = {}
139
- for key in output_fields:
140
- if 'mime_type' not in key:
141
- try:
142
- output_data['content'][key] = json.loads(span['attributes'][key])
143
- except json.JSONDecodeError as e:
144
- output_data['content'][key] = span['attributes'].get(key, None)
145
- final_span["data"]["output"] = [output_data]
58
+ name_counts = defaultdict(int)
146
59
 
147
- if "llm.model_name" in span["attributes"]:
148
- final_span["info"]["model"] = span["attributes"]["llm.model_name"]
149
- else:
150
- final_span["info"]["model"] = None
151
- if "llm.invocation_parameters" in span["attributes"]:
152
- try:
153
- final_span["info"].update(**json.loads(span["attributes"]["llm.invocation_parameters"]))
154
- except json.JSONDecodeError as e:
155
- print(f"Error in parsing: {e}")
156
-
157
- try:
158
- final_span["extra_info"]["llm_parameters"] = json.loads(span["attributes"]["llm.invocation_parameters"])
159
- except json.JSONDecodeError as e:
160
- final_span["extra_info"]["llm_parameters"] = span["attributes"]["llm.invocation_parameters"]
161
- else:
162
- final_span["extra_info"]["llm_parameters"] = None
60
+ for span in data:
61
+ # 1. For each span add '.{occurence_no}' to the span name, where occurence_no is the number of times the span name has occurred
62
+ span["name_occurrences"] = name_counts[span["name"]]
63
+ name_counts[span["name"]] += 1
64
+ span['name'] = f"{span['name']}.{span['name_occurrences']}"
163
65
 
164
- else:
165
- if "input.value" in span["attributes"]:
166
- try:
167
- final_span["data"]["input"] = json.loads(span["attributes"]["input.value"])
168
- except Exception as e:
169
- final_span["data"]["input"] = span["attributes"]["input.value"]
170
- if "output.value" in span["attributes"]:
171
- try:
172
- final_span["data"]["output"] = json.loads(span["attributes"]["output.value"])
173
- except Exception as e:
174
- final_span["data"]["output"] = span["attributes"]["output.value"]
175
-
176
- final_span["info"]["cost"] = {}
177
- final_span["info"]["tokens"] = {}
178
-
179
- if "model" in final_span["info"]:
180
- model_name = final_span["info"]["model"]
181
-
182
- model_costs = {
183
- "default": {"input_cost_per_token": 0.0, "output_cost_per_token": 0.0}
184
- }
185
- try:
186
- model_costs = get_model_cost()
187
- except Exception as e:
188
- pass
189
-
190
- if "resource" in span:
191
- final_span["info"].update(span["resource"])
192
- if "llm.token_count.prompt" in span['attributes']:
193
- final_span["info"]["tokens"]["prompt_tokens"] = span['attributes']['llm.token_count.prompt']
194
- if "llm.token_count.completion" in span['attributes']:
195
- final_span["info"]["tokens"]["completion_tokens"] = span['attributes']['llm.token_count.completion']
196
- if "llm.token_count.total" in span['attributes']:
197
- final_span["info"]["tokens"]["total_tokens"] = span['attributes']['llm.token_count.total']
198
-
199
- if "info" in final_span:
200
- if "tokens" in final_span["info"]:
201
- if "prompt_tokens" in final_span["info"]["tokens"]:
202
- token_usage = {
203
- "prompt_tokens": final_span["info"]["tokens"]["prompt_tokens"],
204
- "completion_tokens": final_span["info"]["tokens"]["completion_tokens"],
205
- "total_tokens": final_span["info"]["tokens"]["total_tokens"]
206
- }
207
- final_span["info"]["cost"] = calculate_llm_cost(token_usage=token_usage, model_name=model_name, model_costs=model_costs, model_custom_cost=custom_model_cost)
208
- span_map[span_id] = final_span
209
- if parent_id not in parent_children_mapping:
210
- parent_children_mapping[parent_id] = []
211
- parent_children_mapping[parent_id].append(final_span)
212
- ordered_family = get_ordered_family(parent_children_mapping)
213
- data = []
214
- for parent_id in ordered_family:
215
- children = parent_children_mapping[parent_id]
216
- if parent_id in span_map:
217
- parent_type = span_map[parent_id]["type"]
218
- if parent_type == 'agent':
219
- span_map[parent_id]['data']["children"] = children
220
- else:
221
- grand_parent_id = span_map[parent_id]["parent_id"]
222
- parent_children_mapping[grand_parent_id].extend(children)
223
- else:
224
- data = children
66
+ # 2. For each span add hash_id, which is uuid4 based on the span name
67
+ span['hash_id'] = get_uuid(span['name'])
225
68
  return data
226
69
 
227
- def convert_json_format(input_trace, custom_model_cost):
70
+ def convert_json_format(input_trace, custom_model_cost, user_context, user_gt,external_id):
228
71
  """
229
72
  Converts a JSON from one format to UI format, handling nested spans.
230
73
 
@@ -239,7 +82,8 @@ def convert_json_format(input_trace, custom_model_cost):
239
82
  "trace_name": "",
240
83
  "project_name": "",
241
84
  "start_time": convert_time_format(min(item["start_time"] for item in input_trace)),
242
- "end_time": convert_time_format(max(item["end_time"] for item in input_trace))
85
+ "end_time": convert_time_format(max(item["end_time"] for item in input_trace)),
86
+ "external_id": external_id
243
87
  }
244
88
  final_trace["metadata"] = {
245
89
  "tokens": {
@@ -258,36 +102,61 @@ def convert_json_format(input_trace, custom_model_cost):
258
102
  final_trace["network_calls"] = []
259
103
  final_trace["interactions"] = []
260
104
 
261
- # import pdb; pdb.set_trace()
262
-
263
- # Helper to recursively extract cost/token info from all spans
264
- def accumulate_metrics(span):
265
- if span["type"] == "llm" and "info" in span:
266
- info = span["info"]
267
- cost = info.get("cost", {})
268
- tokens = info.get("tokens", {})
269
-
270
- final_trace["metadata"]["tokens"]["prompt_tokens"] += tokens.get("prompt_tokens", 0.0)
271
- final_trace["metadata"]["tokens"]["completion_tokens"] += tokens.get("completion_tokens", 0.0)
272
- final_trace["metadata"]["tokens"]["total_tokens"] += tokens.get("total_tokens", 0.0)
273
-
274
- final_trace["metadata"]["cost"]["input_cost"] += cost.get("input_cost", 0.0)
275
- final_trace["metadata"]["cost"]["output_cost"] += cost.get("output_cost", 0.0)
276
- final_trace["metadata"]["cost"]["total_cost"] += cost.get("total_cost", 0.0)
277
-
278
- # Recursively process children
279
- children = span.get("data", {}).get("children", [])
280
- for child in children:
281
- accumulate_metrics(child)
282
-
283
105
  # Extract and attach spans
284
106
  try:
285
- spans = get_spans(input_trace, custom_model_cost)
107
+ spans = get_spans(input_trace)
108
+ # Add user passed context to the trace
109
+ try:
110
+ if user_context:
111
+ spans.append(custom_spans(user_context, "Context", input_trace[0]["context"]["trace_id"], spans[0].get("parent_id")))
112
+ except Exception as e:
113
+ print(f"Error in adding context: {e}")
114
+ return None
115
+
116
+ try:
117
+ if user_gt:
118
+ spans.append(custom_spans(user_gt, "GroundTruth", input_trace[0]["context"]["trace_id"], spans[0].get("parent_id")))
119
+ except Exception as e:
120
+ print(f"Error in adding ground truth: {e}")
121
+ return None
122
+
123
+
286
124
  final_trace["data"][0]["spans"] = spans
125
+
287
126
 
288
- # Accumulate from root spans and their children
127
+ # TODO: each span has token value from prompt ,completion and total tokens. i want the sum of all these tokens for each span
128
+ # Calculate token counts and costs from spans
289
129
  for span in spans:
290
- accumulate_metrics(span)
130
+ if "attributes" in span:
131
+ # Extract token counts
132
+ prompt_tokens = span["attributes"].get("llm.token_count.prompt", 0)
133
+ completion_tokens = span["attributes"].get("llm.token_count.completion", 0)
134
+
135
+ # Update token counts
136
+ final_trace["metadata"]["tokens"]["prompt_tokens"] += prompt_tokens
137
+ final_trace["metadata"]["tokens"]["completion_tokens"] += completion_tokens
138
+ final_trace["metadata"]["tokens"]["total_tokens"] += prompt_tokens + completion_tokens
139
+
140
+ # Get model name from the last span
141
+ model_name = span["attributes"].get("llm.model_name", "")
142
+ if model_name:
143
+ try:
144
+ model_costs = get_model_cost()
145
+ span_cost = calculate_llm_cost(
146
+ {"prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens, "total_tokens": prompt_tokens + completion_tokens},
147
+ model_name,
148
+ model_costs,
149
+ custom_model_cost
150
+ )
151
+ final_trace["metadata"]["cost"]["input_cost"] += span_cost["input_cost"]
152
+ final_trace["metadata"]["cost"]["output_cost"] += span_cost["output_cost"]
153
+ final_trace["metadata"]["cost"]["total_cost"] += span_cost["total_cost"]
154
+
155
+ # Add cost to span attributes for debugging
156
+ span["attributes"]["llm.cost"] = span_cost
157
+ except Exception as e:
158
+ logger.warning(f"Failed to calculate span cost: {e}")
159
+
291
160
  except Exception as e:
292
161
  raise Exception(f"Error in get_spans function: {e}")
293
162
 
@@ -297,7 +166,56 @@ def convert_json_format(input_trace, custom_model_cost):
297
166
 
298
167
  return final_trace
299
168
 
300
-
169
+ def custom_spans(text, span_type, trace_id, parent_id):
170
+ try:
171
+ return {
172
+ "name": f"Custom{span_type}Span",
173
+ "context": {
174
+ "trace_id": trace_id,
175
+ "span_id": f"0x{uuid.uuid4().hex[:16]}",
176
+ "trace_state": "[]"
177
+ },
178
+ "kind": "SpanKind.INTERNAL",
179
+ "parent_id": parent_id,
180
+ "start_time": convert_time_format(datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%fZ")),
181
+ "end_time": convert_time_format(datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%fZ")),
182
+ "status": {
183
+ "status_code": "OK"
184
+ },
185
+ "attributes": {
186
+ "input.value": text,
187
+ "openinference.span.kind": "UNKNOWN"
188
+ },
189
+ "events": [],
190
+ "name_occurrences": 0,
191
+ "hash_id": get_uuid(f"Custom{span_type}Span")
192
+ }
193
+ except Exception as e:
194
+ logger.warning(f"Error in custom_spans function: {e}")
195
+ return {
196
+ "name": f"Custom{span_type}Span",
197
+ "context": {
198
+ "trace_id": trace_id,
199
+ "span_id": f"0x{uuid.uuid4().hex[:16]}",
200
+ "trace_state": "[]"
201
+ },
202
+ "kind": "SpanKind.INTERNAL",
203
+ "parent_id": parent_id,
204
+ "start_time": convert_time_format(datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%fZ")),
205
+ "end_time": convert_time_format(datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%fZ")),
206
+ "status": {
207
+ "status_code": "ERROR",
208
+ "description": str(e)
209
+ },
210
+ "attributes": {
211
+ "input.value": text,
212
+ "openinference.span.kind": "UNKNOWN"
213
+ },
214
+ "events": [],
215
+ "name_occurrences": 0,
216
+ "hash_id": get_uuid(f"Custom{span_type}Span")
217
+ }
218
+
301
219
  if __name__ == "__main__":
302
220
  if len(sys.argv) != 3:
303
221
  print("Usage: python convert.py <input_openinference_trace_path> <output_trace_path>")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ragaai_catalyst
3
- Version: 2.1.7.5b5
3
+ Version: 2.2
4
4
  Summary: RAGA AI CATALYST
5
5
  Author-email: Kiran Scaria <kiran.scaria@raga.ai>, Kedar Gaikwad <kedar.gaikwad@raga.ai>, Dushyant Mahajan <dushyant.mahajan@raga.ai>, Siddhartha Kosti <siddhartha.kosti@raga.ai>, Ritika Goel <ritika.goel@raga.ai>, Vijay Chaurasia <vijay.chaurasia@raga.ai>, Tushar Kumar <tushar.kumar@raga.ai>
6
6
  Requires-Python: <=3.13.2,>=3.10
@@ -31,7 +31,7 @@ ragaai_catalyst/tracers/distributed.py,sha256=MwlBwIxCAng-OI-7Ove_rkE1mTLeuW4Jw-
31
31
  ragaai_catalyst/tracers/langchain_callback.py,sha256=CB75zzG3-DkYTELj0vI1MOHQTY0MuQJfoHIXz9Cl8S8,34568
32
32
  ragaai_catalyst/tracers/llamaindex_callback.py,sha256=ZY0BJrrlz-P9Mg2dX-ZkVKG3gSvzwqBtk7JL_05MiYA,14028
33
33
  ragaai_catalyst/tracers/llamaindex_instrumentation.py,sha256=Ys_jLkvVqo12bKgXDmkp4TxJu9HkBATrFE8cIcTYxWw,14329
34
- ragaai_catalyst/tracers/tracer.py,sha256=w9Poa2dsN3WNMPEH_v4M7SqFF_MQp_iSam4A-qcoAXM,43921
34
+ ragaai_catalyst/tracers/tracer.py,sha256=hdQK3-zV14lBqz8B6gLrMLNtfV34BmJ4-7eiNeLABq8,41931
35
35
  ragaai_catalyst/tracers/upload_traces.py,sha256=w1clGGfdOMpStUJX40NAlxe6dcFdN4pwcezyII0bGYA,6994
36
36
  ragaai_catalyst/tracers/agentic_tracing/README.md,sha256=X4QwLb7-Jg7GQMIXj-SerZIgDETfw-7VgYlczOR8ZeQ,4508
37
37
  ragaai_catalyst/tracers/agentic_tracing/__init__.py,sha256=yf6SKvOPSpH-9LiKaoLKXwqj5sez8F_5wkOb91yp0oE,260
@@ -45,7 +45,7 @@ ragaai_catalyst/tracers/agentic_tracing/tests/ai_travel_agent.py,sha256=S4rCcKzU
45
45
  ragaai_catalyst/tracers/agentic_tracing/tests/unique_decorator_test.py,sha256=Xk1cLzs-2A3dgyBwRRnCWs7Eubki40FVonwd433hPN8,4805
46
46
  ragaai_catalyst/tracers/agentic_tracing/tracers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
47
47
  ragaai_catalyst/tracers/agentic_tracing/tracers/agent_tracer.py,sha256=LzbsHvELwBmH8ObFomJRhiQ98b6MEi18irm0DPiplt0,29743
48
- ragaai_catalyst/tracers/agentic_tracing/tracers/base.py,sha256=wYdGud8JKBnr78fizMGwTdA8qWRMpQyA2Il7tS3rSRU,55823
48
+ ragaai_catalyst/tracers/agentic_tracing/tracers/base.py,sha256=SBTpHP-sFw_Qm581wlnfZCh4XF12qP6BTN0GTrbQ8nc,55365
49
49
  ragaai_catalyst/tracers/agentic_tracing/tracers/custom_tracer.py,sha256=OBJJjFSvwRjCGNJyqX3yIfC1W05ZN2QUXasCJ4gmCjQ,13930
50
50
  ragaai_catalyst/tracers/agentic_tracing/tracers/langgraph_tracer.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
51
51
  ragaai_catalyst/tracers/agentic_tracing/tracers/llm_tracer.py,sha256=z-qzmCQCkhyW0aLDUR_rNq4pmxhAaVhNY-kZQsox-Ws,50221
@@ -54,14 +54,13 @@ ragaai_catalyst/tracers/agentic_tracing/tracers/network_tracer.py,sha256=m8CxYkl
54
54
  ragaai_catalyst/tracers/agentic_tracing/tracers/tool_tracer.py,sha256=xxrliKPfdfbIZRZqMnUewsaTD8_Hv0dbuoBivNZGD4U,21674
55
55
  ragaai_catalyst/tracers/agentic_tracing/tracers/user_interaction_tracer.py,sha256=bhSUhNQCuJXKjgJAXhjKEYjnHMpYN90FSZdR84fNIKU,4614
56
56
  ragaai_catalyst/tracers/agentic_tracing/upload/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
57
- ragaai_catalyst/tracers/agentic_tracing/upload/trace_uploader.py,sha256=qGinKWnb-NSEfIfIOsL37tB9AS8-dKa_-nNNHkUmtuE,12955
58
- ragaai_catalyst/tracers/agentic_tracing/upload/upload_agentic_traces.py,sha256=u7QwUbG73zeWi-5WQ4scLo7wfw184Qd8c03TxgfoUe4,9567
57
+ ragaai_catalyst/tracers/agentic_tracing/upload/trace_uploader.py,sha256=FqHjvFdq5Pqp8iZcLTwXaxnMmm8ATec3fLdDuzLITFs,13019
58
+ ragaai_catalyst/tracers/agentic_tracing/upload/upload_agentic_traces.py,sha256=sdeUz2zYTHCNh82K6-I1RmQw7jsnGzJVe1VVglKcb_4,8082
59
59
  ragaai_catalyst/tracers/agentic_tracing/upload/upload_code.py,sha256=eNjKt8xC2IIs_mC9WdLaP_vUxWpYHVi2OXgJyn2oSx8,7443
60
60
  ragaai_catalyst/tracers/agentic_tracing/upload/upload_local_metric.py,sha256=m1O8lKpxKwtHofXLW3fTHX5yfqDW5GxoveARlg5cTw4,2571
61
- ragaai_catalyst/tracers/agentic_tracing/upload/upload_trace_metric.py,sha256=hRuh-cczHbeM_Spbf9HTYd149uSs1zP0TvkYuZKF4ec,4296
62
61
  ragaai_catalyst/tracers/agentic_tracing/utils/__init__.py,sha256=XdB3X_ufe4RVvGorxSqAiB9dYv4UD7Hvvuw3bsDUppY,60
63
62
  ragaai_catalyst/tracers/agentic_tracing/utils/api_utils.py,sha256=JyNCbfpW-w4O9CjtemTqmor2Rh1WGpQwhRaDSRmBxw8,689
64
- ragaai_catalyst/tracers/agentic_tracing/utils/create_dataset_schema.py,sha256=TQ69gOp1UDV16Icp7uhWKXkadPsOnZgkHRgNvsi7jlg,959
63
+ ragaai_catalyst/tracers/agentic_tracing/utils/create_dataset_schema.py,sha256=KxxIuuB7-TIfXdwaJsAgKsG90S2tOTS021mimCOczwc,1543
65
64
  ragaai_catalyst/tracers/agentic_tracing/utils/file_name_tracker.py,sha256=YG601l1a29ov9VPu9Vl4RXxgL7l16k54_WWnoTNoG58,2064
66
65
  ragaai_catalyst/tracers/agentic_tracing/utils/generic.py,sha256=WwXT01xmp8MSr7KinuDCSK9a1ifpLcT7ajFkvYviG_A,1190
67
66
  ragaai_catalyst/tracers/agentic_tracing/utils/get_user_trace_metrics.py,sha256=vPZ4dn4EHFW0kqd1GyRpsYXbfrRrd0DXCmh-pzsDBNE,1109
@@ -74,10 +73,10 @@ ragaai_catalyst/tracers/agentic_tracing/utils/trace_utils.py,sha256=W7Nw-IpugejI
74
73
  ragaai_catalyst/tracers/agentic_tracing/utils/unique_decorator.py,sha256=G027toV-Km20JjKrc-Y_PilQ8ABEKrBvvzgLTnqVg7I,5819
75
74
  ragaai_catalyst/tracers/agentic_tracing/utils/zip_list_of_unique_files.py,sha256=4TeCGsFF26249fV6dJHLTZDrRa93SG9oer4rudoF8Y4,19443
76
75
  ragaai_catalyst/tracers/exporters/__init__.py,sha256=wQbaqyeIjVZxYprHCKZ9BeiqxeXYBKjzEgP79LWNxCU,293
77
- ragaai_catalyst/tracers/exporters/dynamic_trace_exporter.py,sha256=v2V-y1l9t9gQQbqoi2jlEhm1xRQjR5yTyr6rxSriXCE,6303
76
+ ragaai_catalyst/tracers/exporters/dynamic_trace_exporter.py,sha256=JhYVSN9t6-9MFcg0IrYEJIyD6rg9O96Arg2poQSb5g8,6855
78
77
  ragaai_catalyst/tracers/exporters/file_span_exporter.py,sha256=RgGteu-NVGprXKkynvyIO5yOjpbtA41R3W_NzCjnkwE,6445
79
78
  ragaai_catalyst/tracers/exporters/raga_exporter.py,sha256=6xvjWXyh8XPkHKSLLmAZUQSvwuyY17ov8pv2VdfI0qA,17875
80
- ragaai_catalyst/tracers/exporters/ragaai_trace_exporter.py,sha256=C88pZ_n4mNv1Fc3qOOOm5JQdoTvQzHcjS7mSImslQ0I,13313
79
+ ragaai_catalyst/tracers/exporters/ragaai_trace_exporter.py,sha256=exiAHrHlMPWwwlQnMFeAYwjeicgUjCL97OKPHl-g5GI,9275
81
80
  ragaai_catalyst/tracers/instrumentators/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
82
81
  ragaai_catalyst/tracers/utils/__init__.py,sha256=KeMaZtYaTojilpLv65qH08QmpYclfpacDA0U3wg6Ybw,64
83
82
  ragaai_catalyst/tracers/utils/convert_langchain_callbacks_output.py,sha256=SehrD7q8ytAiUYoWr406b4mWs3Lk0Rcy6Ekkihh22TI,1703
@@ -85,11 +84,12 @@ ragaai_catalyst/tracers/utils/convert_llama_instru_callback.py,sha256=8qLo7x4Zsn
85
84
  ragaai_catalyst/tracers/utils/extraction_logic_llama_index.py,sha256=ZhPs0YhVtB82-Pq9o1BvCinKE_WPvVxPTEcZjlJbFYM,2371
86
85
  ragaai_catalyst/tracers/utils/langchain_tracer_extraction_logic.py,sha256=XS2_x2qneqEx9oAighLg-LRiueWcESLwIC2r7eJT-Ww,3117
87
86
  ragaai_catalyst/tracers/utils/model_prices_and_context_window_backup.json,sha256=C3uwkibJ08C9sOX-54kulZYmJlIpZ-SQpfE6HNGrjbM,343502
88
- ragaai_catalyst/tracers/utils/rag_trace_json_converter.py,sha256=adCKk7Nj8307XYYg2sB-QT-66OShOs2iTGwNVwqbHig,19373
89
- ragaai_catalyst/tracers/utils/trace_json_converter.py,sha256=E0_QfciQMMpCtQYrNB4l8HJhlaFalr5bkMqkVRgQahY,14073
87
+ ragaai_catalyst/tracers/utils/rag_extraction_logic_final.py,sha256=3ygkRT__lLDRflRttjzPu28tIA8cTCiGQVMQjqMItqQ,11309
88
+ ragaai_catalyst/tracers/utils/rag_trace_json_converter.py,sha256=54IEZO-YRjUAahV5nw8KClXqTF1LhfDry_TsZ4KGow4,20467
89
+ ragaai_catalyst/tracers/utils/trace_json_converter.py,sha256=K4X4yUmB01UtFX-_xmJsgFOAmzGe8qQ6SYQRHUyWlKs,9405
90
90
  ragaai_catalyst/tracers/utils/utils.py,sha256=ViygfJ7vZ7U0CTSA1lbxVloHp4NSlmfDzBRNCJuMhis,2374
91
- ragaai_catalyst-2.1.7.5b5.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
92
- ragaai_catalyst-2.1.7.5b5.dist-info/METADATA,sha256=qTUNGuVyjtbjoOnA2Zq_HARkI0TgkYnYj8qDU7W33aE,17607
93
- ragaai_catalyst-2.1.7.5b5.dist-info/WHEEL,sha256=Nw36Djuh_5VDukK0H78QzOX-_FQEo6V37m3nkm96gtU,91
94
- ragaai_catalyst-2.1.7.5b5.dist-info/top_level.txt,sha256=HpgsdRgEJMk8nqrU6qdCYk3di7MJkDL0B19lkc7dLfM,16
95
- ragaai_catalyst-2.1.7.5b5.dist-info/RECORD,,
91
+ ragaai_catalyst-2.2.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
92
+ ragaai_catalyst-2.2.dist-info/METADATA,sha256=rytHjlVJ46jQhFTVDo8fuT7k5HupO4ue6dxAXQ_v0u4,17601
93
+ ragaai_catalyst-2.2.dist-info/WHEEL,sha256=Nw36Djuh_5VDukK0H78QzOX-_FQEo6V37m3nkm96gtU,91
94
+ ragaai_catalyst-2.2.dist-info/top_level.txt,sha256=HpgsdRgEJMk8nqrU6qdCYk3di7MJkDL0B19lkc7dLfM,16
95
+ ragaai_catalyst-2.2.dist-info/RECORD,,
@@ -1,114 +0,0 @@
1
- import logging
2
-
3
- import requests
4
- import os
5
- import json
6
- import time
7
- from ....ragaai_catalyst import RagaAICatalyst
8
- from ..utils.get_user_trace_metrics import get_user_trace_metrics
9
-
10
- logger = logging.getLogger(__name__)
11
- logging_level = (
12
- logger.setLevel(logging.DEBUG)
13
- if os.getenv("DEBUG")
14
- else logger.setLevel(logging.INFO)
15
- )
16
-
17
-
18
- def upload_trace_metric(json_file_path, dataset_name, project_name, base_url=None, timeout=120):
19
- try:
20
- with open(json_file_path, "r") as f:
21
- traces = json.load(f)
22
-
23
- metrics = get_trace_metrics_from_trace(traces)
24
- metrics = _change_metrics_format_for_payload(metrics)
25
-
26
- user_trace_metrics = get_user_trace_metrics(project_name, dataset_name)
27
- if user_trace_metrics:
28
- user_trace_metrics_list = [metric["displayName"] for metric in user_trace_metrics]
29
-
30
- if user_trace_metrics:
31
- for metric in metrics:
32
- if metric["displayName"] in user_trace_metrics_list:
33
- metricConfig = next((user_metric["metricConfig"] for user_metric in user_trace_metrics if
34
- user_metric["displayName"] == metric["displayName"]), None)
35
- if not metricConfig or metricConfig.get("Metric Source", {}).get("value") != "user":
36
- raise ValueError(
37
- f"Metrics {metric['displayName']} already exist in dataset {dataset_name} of project {project_name}.")
38
- headers = {
39
- "Content-Type": "application/json",
40
- "Authorization": f"Bearer {os.getenv('RAGAAI_CATALYST_TOKEN')}",
41
- "X-Project-Name": project_name,
42
- }
43
- payload = json.dumps({
44
- "datasetName": dataset_name,
45
- "metrics": metrics
46
- })
47
- url_base = base_url if base_url is not None else RagaAICatalyst.BASE_URL
48
- start_time = time.time()
49
- endpoint = f"{url_base}/v1/llm/trace/metrics"
50
- response = requests.request("POST",
51
- endpoint,
52
- headers=headers,
53
- data=payload,
54
- timeout=timeout)
55
- elapsed_ms = (time.time() - start_time) * 1000
56
- logger.debug(
57
- f"API Call: [POST] {endpoint} | Status: {response.status_code} | Time: {elapsed_ms:.2f}ms")
58
- if response.status_code != 200:
59
- raise ValueError(f"Error inserting agentic trace metrics")
60
- except requests.exceptions.RequestException as e:
61
- raise ValueError(f"Error submitting traces: {e}")
62
- return None
63
-
64
- return response
65
-
66
-
67
- def _get_children_metrics_of_agent(children_traces):
68
- metrics = []
69
- for span in children_traces:
70
- metrics.extend(span.get("metrics", []))
71
- if span["type"] != "agent":
72
- metric = span.get("metrics", [])
73
- if metric:
74
- metrics.extend(metric)
75
- else:
76
- metrics.extend(_get_children_metrics_of_agent(span["data"]["children"]))
77
- return metrics
78
-
79
- def get_trace_metrics_from_trace(traces):
80
- metrics = []
81
-
82
- # get trace level metrics
83
- if "metrics" in traces.keys():
84
- if len(traces["metrics"]) > 0:
85
- metrics.extend(traces["metrics"])
86
-
87
- # get span level metrics
88
- for span in traces["data"][0]["spans"]:
89
- if span["type"] == "agent":
90
- # Add children metrics of agent
91
- children_metric = _get_children_metrics_of_agent(span["data"]["children"])
92
- if children_metric:
93
- metrics.extend(children_metric)
94
-
95
- metric = span.get("metrics", [])
96
- if metric:
97
- metrics.extend(metric)
98
- return metrics
99
-
100
-
101
- def _change_metrics_format_for_payload(metrics):
102
- formatted_metrics = []
103
- for metric in metrics:
104
- if any(m["name"] == metric.get("displayName") or m['name'] == metric.get("name") for m in formatted_metrics):
105
- continue
106
- metric_display_name = metric["name"]
107
- if metric.get("displayName"):
108
- metric_display_name = metric['displayName']
109
- formatted_metrics.append({
110
- "name": metric_display_name,
111
- "displayName": metric_display_name,
112
- "config": {"source": "user"},
113
- })
114
- return formatted_metrics