monocle-apptrace 0.1.1__py3-none-any.whl → 0.3.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.

Potentially problematic release.


This version of monocle-apptrace might be problematic. Click here for more details.

Files changed (88) hide show
  1. monocle_apptrace/__init__.py +1 -0
  2. monocle_apptrace/__main__.py +19 -0
  3. monocle_apptrace/exporters/aws/s3_exporter.py +181 -0
  4. monocle_apptrace/exporters/aws/s3_exporter_opendal.py +137 -0
  5. monocle_apptrace/exporters/azure/blob_exporter.py +146 -0
  6. monocle_apptrace/exporters/azure/blob_exporter_opendal.py +162 -0
  7. monocle_apptrace/exporters/base_exporter.py +48 -0
  8. monocle_apptrace/exporters/exporter_processor.py +144 -0
  9. monocle_apptrace/exporters/file_exporter.py +16 -0
  10. monocle_apptrace/exporters/monocle_exporters.py +55 -0
  11. monocle_apptrace/exporters/okahu/okahu_exporter.py +117 -0
  12. monocle_apptrace/instrumentation/__init__.py +1 -0
  13. monocle_apptrace/instrumentation/common/__init__.py +2 -0
  14. monocle_apptrace/instrumentation/common/constants.py +70 -0
  15. monocle_apptrace/instrumentation/common/instrumentor.py +362 -0
  16. monocle_apptrace/instrumentation/common/span_handler.py +220 -0
  17. monocle_apptrace/instrumentation/common/utils.py +356 -0
  18. monocle_apptrace/instrumentation/common/wrapper.py +92 -0
  19. monocle_apptrace/instrumentation/common/wrapper_method.py +72 -0
  20. monocle_apptrace/instrumentation/metamodel/__init__.py +0 -0
  21. monocle_apptrace/instrumentation/metamodel/botocore/__init__.py +0 -0
  22. monocle_apptrace/instrumentation/metamodel/botocore/_helper.py +95 -0
  23. monocle_apptrace/instrumentation/metamodel/botocore/entities/__init__.py +0 -0
  24. monocle_apptrace/instrumentation/metamodel/botocore/entities/inference.py +65 -0
  25. monocle_apptrace/instrumentation/metamodel/botocore/handlers/botocore_span_handler.py +26 -0
  26. monocle_apptrace/instrumentation/metamodel/botocore/methods.py +16 -0
  27. monocle_apptrace/instrumentation/metamodel/flask/__init__.py +0 -0
  28. monocle_apptrace/instrumentation/metamodel/flask/_helper.py +29 -0
  29. monocle_apptrace/instrumentation/metamodel/flask/methods.py +13 -0
  30. monocle_apptrace/instrumentation/metamodel/haystack/__init__.py +0 -0
  31. monocle_apptrace/instrumentation/metamodel/haystack/_helper.py +127 -0
  32. monocle_apptrace/instrumentation/metamodel/haystack/entities/__init__.py +0 -0
  33. monocle_apptrace/instrumentation/metamodel/haystack/entities/inference.py +76 -0
  34. monocle_apptrace/instrumentation/metamodel/haystack/entities/retrieval.py +61 -0
  35. monocle_apptrace/instrumentation/metamodel/haystack/methods.py +43 -0
  36. monocle_apptrace/instrumentation/metamodel/langchain/__init__.py +0 -0
  37. monocle_apptrace/instrumentation/metamodel/langchain/_helper.py +127 -0
  38. monocle_apptrace/instrumentation/metamodel/langchain/entities/__init__.py +0 -0
  39. monocle_apptrace/instrumentation/metamodel/langchain/entities/inference.py +72 -0
  40. monocle_apptrace/instrumentation/metamodel/langchain/entities/retrieval.py +58 -0
  41. monocle_apptrace/{metamodel/maps/lang_chain_methods.json → instrumentation/metamodel/langchain/methods.py} +48 -43
  42. monocle_apptrace/instrumentation/metamodel/langgraph/__init__.py +0 -0
  43. monocle_apptrace/instrumentation/metamodel/langgraph/_helper.py +48 -0
  44. monocle_apptrace/instrumentation/metamodel/langgraph/entities/__init__.py +0 -0
  45. monocle_apptrace/instrumentation/metamodel/langgraph/entities/inference.py +56 -0
  46. monocle_apptrace/instrumentation/metamodel/langgraph/methods.py +14 -0
  47. monocle_apptrace/instrumentation/metamodel/llamaindex/__init__.py +0 -0
  48. monocle_apptrace/instrumentation/metamodel/llamaindex/_helper.py +172 -0
  49. monocle_apptrace/instrumentation/metamodel/llamaindex/entities/__init__.py +0 -0
  50. monocle_apptrace/instrumentation/metamodel/llamaindex/entities/agent.py +47 -0
  51. monocle_apptrace/instrumentation/metamodel/llamaindex/entities/inference.py +73 -0
  52. monocle_apptrace/instrumentation/metamodel/llamaindex/entities/retrieval.py +57 -0
  53. monocle_apptrace/instrumentation/metamodel/llamaindex/methods.py +101 -0
  54. monocle_apptrace/instrumentation/metamodel/openai/__init__.py +0 -0
  55. monocle_apptrace/instrumentation/metamodel/openai/_helper.py +112 -0
  56. monocle_apptrace/instrumentation/metamodel/openai/entities/__init__.py +0 -0
  57. monocle_apptrace/instrumentation/metamodel/openai/entities/inference.py +71 -0
  58. monocle_apptrace/instrumentation/metamodel/openai/entities/retrieval.py +43 -0
  59. monocle_apptrace/instrumentation/metamodel/openai/methods.py +45 -0
  60. monocle_apptrace/instrumentation/metamodel/requests/__init__.py +4 -0
  61. monocle_apptrace/instrumentation/metamodel/requests/_helper.py +31 -0
  62. monocle_apptrace/instrumentation/metamodel/requests/methods.py +12 -0
  63. {monocle_apptrace-0.1.1.dist-info → monocle_apptrace-0.3.0.dist-info}/METADATA +23 -2
  64. monocle_apptrace-0.3.0.dist-info/RECORD +68 -0
  65. {monocle_apptrace-0.1.1.dist-info → monocle_apptrace-0.3.0.dist-info}/WHEEL +1 -1
  66. monocle_apptrace/constants.py +0 -22
  67. monocle_apptrace/haystack/__init__.py +0 -9
  68. monocle_apptrace/haystack/wrap_node.py +0 -27
  69. monocle_apptrace/haystack/wrap_openai.py +0 -44
  70. monocle_apptrace/haystack/wrap_pipeline.py +0 -62
  71. monocle_apptrace/instrumentor.py +0 -124
  72. monocle_apptrace/langchain/__init__.py +0 -6
  73. monocle_apptrace/llamaindex/__init__.py +0 -15
  74. monocle_apptrace/metamodel/README.md +0 -47
  75. monocle_apptrace/metamodel/entities/README.md +0 -54
  76. monocle_apptrace/metamodel/entities/entity_types.json +0 -157
  77. monocle_apptrace/metamodel/entities/entity_types.py +0 -51
  78. monocle_apptrace/metamodel/maps/haystack_methods.json +0 -25
  79. monocle_apptrace/metamodel/maps/llama_index_methods.json +0 -70
  80. monocle_apptrace/metamodel/spans/README.md +0 -121
  81. monocle_apptrace/metamodel/spans/span_example.json +0 -140
  82. monocle_apptrace/metamodel/spans/span_format.json +0 -55
  83. monocle_apptrace/utils.py +0 -93
  84. monocle_apptrace/wrap_common.py +0 -311
  85. monocle_apptrace/wrapper.py +0 -24
  86. monocle_apptrace-0.1.1.dist-info/RECORD +0 -29
  87. {monocle_apptrace-0.1.1.dist-info → monocle_apptrace-0.3.0.dist-info}/licenses/LICENSE +0 -0
  88. {monocle_apptrace-0.1.1.dist-info → monocle_apptrace-0.3.0.dist-info}/licenses/NOTICE +0 -0
@@ -0,0 +1,26 @@
1
+ from opentelemetry.context import get_value, set_value, attach, detach
2
+ from monocle_apptrace.instrumentation.common.span_handler import SpanHandler
3
+
4
+ class BotoCoreSpanHandler(SpanHandler):
5
+
6
+ def _botocore_processor(self, to_wrap, wrapped, instance, args, kwargs, return_value):
7
+ service_name = kwargs.get("service_name")
8
+ service_method_mapping = {
9
+ "sagemaker-runtime": "invoke_endpoint",
10
+ "bedrock-runtime": "converse",
11
+ }
12
+ if service_name in service_method_mapping:
13
+ method_name = service_method_mapping[service_name]
14
+ original_method = getattr(return_value, method_name, None)
15
+ span_name = "botocore-" + service_name + "-invoke-endpoint"
16
+ # wrap_util(original_method, span_name)
17
+ if original_method:
18
+ instrumentor = self.instrumentor
19
+ if instrumentor:
20
+ instrumented_method = instrumentor(to_wrap, wrapped, span_name, return_value, original_method)
21
+ setattr(return_value, method_name, instrumented_method)
22
+
23
+ def post_tracing(self, to_wrap, wrapped, instance, args, kwargs, return_value):
24
+ self._botocore_processor(to_wrap=to_wrap, wrapped=wrapped, instance=instance, return_value=return_value, args=args,
25
+ kwargs=kwargs)
26
+ return super().pre_tracing(to_wrap, wrapped, instance, args, kwargs)
@@ -0,0 +1,16 @@
1
+ from monocle_apptrace.instrumentation.common.wrapper import task_wrapper
2
+ from monocle_apptrace.instrumentation.metamodel.botocore.entities.inference import (
3
+ INFERENCE,
4
+ )
5
+
6
+ BOTOCORE_METHODS = [
7
+ {
8
+ "package": "botocore.client",
9
+ "object": "ClientCreator",
10
+ "method": "create_client",
11
+ "wrapper_method": task_wrapper,
12
+ "span_handler":"botocore_handler",
13
+ "output_processor": INFERENCE,
14
+ "skip_span": True
15
+ }
16
+ ]
@@ -0,0 +1,29 @@
1
+ from threading import local
2
+ from monocle_apptrace.instrumentation.common.utils import extract_http_headers, clear_http_scopes
3
+ from opentelemetry.propagate import extract
4
+ from opentelemetry.context import Context, attach, detach
5
+ from monocle_apptrace.instrumentation.common.span_handler import SpanHandler
6
+ token_data = local()
7
+ token_data.current_token = None
8
+
9
+ def flask_pre_tracing(args):
10
+ headers = dict()
11
+ for key, value in args[0].items():
12
+ if key.startswith("HTTP_"):
13
+ new_key = key[5:].lower().replace("_", "-")
14
+ headers[new_key] = value
15
+ token_data.current_token = extract_http_headers(headers)
16
+
17
+ def flask_post_tracing():
18
+ clear_http_scopes(token_data.current_token)
19
+ token_data.current_token = None
20
+
21
+ class FlaskSpanHandler(SpanHandler):
22
+
23
+ def pre_tracing(self, to_wrap, wrapped, instance, args, kwargs):
24
+ flask_pre_tracing(args)
25
+ return super().pre_tracing(to_wrap, wrapped, instance, args, kwargs)
26
+
27
+ def post_tracing(self, to_wrap, wrapped, instance, args, kwargs, return_value):
28
+ flask_post_tracing()
29
+ return super().post_tracing(to_wrap, wrapped, instance, args, kwargs, return_value)
@@ -0,0 +1,13 @@
1
+ from monocle_apptrace.instrumentation.common.wrapper import task_wrapper
2
+
3
+ FLASK_METHODS = [
4
+ {
5
+ "package": "flask.app",
6
+ "object": "Flask",
7
+ "method": "wsgi_app",
8
+ "span_name": "Flask.wsgi_app",
9
+ "wrapper_method": task_wrapper,
10
+ "span_handler": "flask_handler",
11
+ "skip_span": True
12
+ }
13
+ ]
@@ -0,0 +1,127 @@
1
+ import logging
2
+ from monocle_apptrace.instrumentation.common.utils import (
3
+ Option,
4
+ get_keys_as_tuple,
5
+ get_nested_value,
6
+ try_option,
7
+ )
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def extract_messages(kwargs):
12
+ try:
13
+ messages = []
14
+ if isinstance(kwargs, dict):
15
+ if 'system_prompt' in kwargs and kwargs['system_prompt']:
16
+ system_message = kwargs['system_prompt']
17
+ messages.append({"system" : system_message})
18
+ if 'prompt' in kwargs and kwargs['prompt']:
19
+ user_message = extract_question_from_prompt(kwargs['prompt'])
20
+ messages.append({"user": user_message})
21
+ return [str(message) for message in messages]
22
+ except Exception as e:
23
+ logger.warning("Warning: Error occurred in extract_messages: %s", str(e))
24
+ return []
25
+
26
+
27
+ def extract_question_from_prompt(content):
28
+ try:
29
+ question_prefix = "Question:"
30
+ answer_prefix = "Answer:"
31
+
32
+ question_start = content.find(question_prefix)
33
+ if question_start == -1:
34
+ return None # Return None if "Question:" is not found
35
+
36
+ question_start += len(question_prefix)
37
+ answer_start = content.find(answer_prefix, question_start)
38
+ if answer_start == -1:
39
+ question = content[question_start:].strip()
40
+ else:
41
+ question = content[question_start:answer_start].strip()
42
+
43
+ return question
44
+ except Exception as e:
45
+ logger.warning("Warning: Error occurred in extract_question_from_prompt: %s", str(e))
46
+ return ""
47
+
48
+
49
+ def extract_assistant_message(response):
50
+ try:
51
+ if "replies" in response:
52
+ reply = response["replies"][0]
53
+ if hasattr(reply, 'content'):
54
+ return [reply.content]
55
+ return [reply]
56
+ except Exception as e:
57
+ logger.warning("Warning: Error occurred in extract_assistant_message: %s", str(e))
58
+ return []
59
+
60
+
61
+ def get_vectorstore_deployment(my_map):
62
+ if isinstance(my_map, dict):
63
+ if '_client_settings' in my_map:
64
+ client = my_map['_client_settings'].__dict__
65
+ host, port = get_keys_as_tuple(client, 'host', 'port')
66
+ if host:
67
+ return f"{host}:{port}" if port else host
68
+ keys_to_check = ['client', '_client']
69
+ host = get_host_from_map(my_map, keys_to_check)
70
+ if host:
71
+ return host
72
+ else:
73
+ if hasattr(my_map, 'client') and '_endpoint' in my_map.client.__dict__:
74
+ return my_map.client.__dict__['_endpoint']
75
+ host, port = get_keys_as_tuple(my_map.__dict__, 'host', 'port')
76
+ if host:
77
+ return f"{host}:{port}" if port else host
78
+ return None
79
+
80
+
81
+ def get_host_from_map(my_map, keys_to_check):
82
+ for key in keys_to_check:
83
+ seed_connections = get_nested_value(my_map, [key, 'transport', 'seed_connections'])
84
+ if seed_connections and 'host' in seed_connections[0].__dict__:
85
+ return seed_connections[0].__dict__['host']
86
+ return None
87
+
88
+
89
+ def resolve_from_alias(my_map, alias):
90
+ """Find a alias that is not none from list of aliases"""
91
+
92
+ for i in alias:
93
+ if i in my_map.keys():
94
+ return my_map[i]
95
+ return None
96
+
97
+ def extract_inference_endpoint(instance):
98
+ inference_endpoint: Option[str] = try_option(getattr, instance.client, 'base_url').map(str)
99
+ if inference_endpoint.is_none():
100
+ inference_endpoint = try_option(getattr, instance.client.meta, 'endpoint_url').map(str)
101
+
102
+ return inference_endpoint.unwrap_or(None)
103
+
104
+ def extract_embeding_model(instance):
105
+ pipeline = try_option(getattr, instance, '__haystack_added_to_pipeline__')
106
+ return pipeline.map(lambda p: try_option(getattr, p, 'get_component').map(
107
+ lambda g: try_option(getattr, g('text_embedder'), 'model').unwrap_or(None)).unwrap_or(None)).unwrap_or(None)
108
+
109
+ def update_span_from_llm_response(response, instance):
110
+ meta_dict = {}
111
+ if response is not None and isinstance(response, dict) and "meta" in response:
112
+ token_usage = response["meta"][0]["usage"]
113
+ if token_usage is not None:
114
+ temperature = instance.__dict__.get("temperature", None)
115
+ meta_dict.update({"temperature": temperature})
116
+ meta_dict.update(
117
+ {"completion_tokens": token_usage.get("completion_tokens") or token_usage.get("output_tokens")})
118
+ meta_dict.update({"prompt_tokens": token_usage.get("prompt_tokens") or token_usage.get("input_tokens")})
119
+ meta_dict.update({"total_tokens": token_usage.get("total_tokens")})
120
+ return meta_dict
121
+
122
+
123
+ def update_output_span_events(results):
124
+ output_arg_text = " ".join([doc.content for doc in results['documents']])
125
+ if len(output_arg_text) > 100:
126
+ output_arg_text = output_arg_text[:100] + "..."
127
+ return output_arg_text
@@ -0,0 +1,76 @@
1
+ from monocle_apptrace.instrumentation.metamodel.haystack import (
2
+ _helper,
3
+ )
4
+
5
+ INFERENCE = {
6
+ "type": "inference",
7
+ "attributes": [
8
+ [
9
+ {
10
+ "_comment": "provider type ,name , deployment , inference_endpoint",
11
+ "attribute": "type",
12
+ "accessor": lambda arguments: 'inference.azure_openai'
13
+ },
14
+ {
15
+ "attribute": "provider_name",
16
+ "accessor": lambda arguments: arguments['kwargs']['provider_name']
17
+ },
18
+ {
19
+ "attribute": "deployment",
20
+ "accessor": lambda arguments: _helper.resolve_from_alias(arguments['instance'].__dict__,
21
+ ['engine', 'azure_deployment',
22
+ 'deployment_name', 'deployment_id',
23
+ 'deployment'])
24
+ },
25
+ {
26
+ "attribute": "inference_endpoint",
27
+ "accessor": lambda arguments: _helper.resolve_from_alias(arguments['instance'].__dict__, ['api_base_url']) or _helper.extract_inference_endpoint(arguments['instance'])
28
+ }
29
+ ],
30
+ [
31
+ {
32
+ "_comment": "LLM Model",
33
+ "attribute": "name",
34
+ "accessor": lambda arguments: _helper.resolve_from_alias(arguments['instance'].__dict__,
35
+ ['model', 'model_name'])
36
+ },
37
+ {
38
+ "attribute": "type",
39
+ "accessor": lambda arguments: 'model.llm.' + _helper.resolve_from_alias(arguments['instance'].__dict__,
40
+ ['model', 'model_name'])
41
+ }
42
+ ]
43
+ ],
44
+ "events": [
45
+ {"name": "data.input",
46
+ "attributes": [
47
+
48
+ {
49
+ "_comment": "this is instruction and user query to LLM",
50
+ "attribute": "input",
51
+ "accessor": lambda arguments: _helper.extract_messages(arguments['kwargs'])
52
+ }
53
+ ]
54
+ },
55
+ {
56
+ "name": "data.output",
57
+ "attributes": [
58
+ {
59
+ "_comment": "this is response from LLM",
60
+ "attribute": "response",
61
+ "accessor": lambda arguments: _helper.extract_assistant_message(arguments['result'])
62
+ }
63
+ ]
64
+ },
65
+ {
66
+ "name": "metadata",
67
+ "attributes": [
68
+ {
69
+ "_comment": "this is metadata usage from LLM",
70
+ "accessor": lambda arguments: _helper.update_span_from_llm_response(arguments['result'],
71
+ arguments['instance'])
72
+ }
73
+ ]
74
+ }
75
+ ]
76
+ }
@@ -0,0 +1,61 @@
1
+ from monocle_apptrace.instrumentation.metamodel.haystack import (_helper, )
2
+ from monocle_apptrace.instrumentation.common.utils import get_attribute
3
+
4
+ RETRIEVAL = {
5
+ "type": "retrieval",
6
+ "attributes": [
7
+ [
8
+ {
9
+ "_comment": "vector store name and type",
10
+ "attribute": "name",
11
+ "accessor": lambda arguments: _helper.resolve_from_alias(arguments['instance'].__dict__,
12
+ ['document_store',
13
+ '_document_store']).__class__.__name__
14
+ },
15
+ {
16
+ "attribute": "type",
17
+ "accessor": lambda arguments: 'vectorstore.' + _helper.resolve_from_alias(
18
+ arguments['instance'].__dict__, ['document_store', '_document_store']).__class__.__name__
19
+ },
20
+ {
21
+ "attribute": "deployment",
22
+ "accessor": lambda arguments: _helper.get_vectorstore_deployment(
23
+ _helper.resolve_from_alias(arguments['instance'].__dict__,
24
+ ['document_store', '_document_store']).__dict__)
25
+ }
26
+ ],
27
+ [
28
+ {
29
+ "_comment": "embedding model name and type",
30
+ "attribute": "name",
31
+ "accessor": lambda arguments: _helper.extract_embeding_model(arguments['instance'])
32
+ },
33
+ {
34
+ "attribute": "type",
35
+ "accessor": lambda arguments: 'model.embedding.' + _helper.extract_embeding_model(arguments['instance'])
36
+ }
37
+ ]
38
+ ],
39
+ "events": [
40
+ {"name": "data.input",
41
+ "attributes": [
42
+
43
+ {
44
+ "_comment": "this is instruction and user query to LLM",
45
+ "attribute": "input",
46
+ "accessor": lambda arguments: get_attribute("input")
47
+ }
48
+ ]
49
+ },
50
+ {
51
+ "name": "data.output",
52
+ "attributes": [
53
+ {
54
+ "_comment": "this is result from LLM",
55
+ "attribute": "response",
56
+ "accessor": lambda arguments: _helper.update_output_span_events(arguments['result'])
57
+ }
58
+ ]
59
+ }
60
+ ]
61
+ }
@@ -0,0 +1,43 @@
1
+ from monocle_apptrace.instrumentation.common.wrapper import task_wrapper
2
+ from monocle_apptrace.instrumentation.metamodel.haystack.entities.inference import INFERENCE
3
+ from monocle_apptrace.instrumentation.metamodel.haystack.entities.retrieval import RETRIEVAL
4
+
5
+ HAYSTACK_METHODS = [
6
+ {
7
+ "package": "haystack.components.retrievers.in_memory",
8
+ "object": "InMemoryEmbeddingRetriever",
9
+ "method": "run",
10
+ "span_name": "haystack.retriever",
11
+ "wrapper_method": task_wrapper,
12
+ "output_processor": RETRIEVAL
13
+ },
14
+ {
15
+ "package": "haystack_integrations.components.retrievers.opensearch",
16
+ "object": "OpenSearchEmbeddingRetriever",
17
+ "method": "run",
18
+ "span_name": "haystack.retriever",
19
+ "wrapper_method": task_wrapper,
20
+ "output_processor": RETRIEVAL
21
+ },
22
+ {
23
+ "package": "haystack.components.generators.openai",
24
+ "object": "OpenAIGenerator",
25
+ "method": "run",
26
+ "wrapper_method": task_wrapper,
27
+ "output_processor": INFERENCE
28
+ },
29
+ {
30
+ "package": "haystack.components.generators.chat.openai",
31
+ "object": "OpenAIChatGenerator",
32
+ "method": "run",
33
+ "wrapper_method": task_wrapper,
34
+ "output_processor": INFERENCE
35
+ },
36
+ {
37
+ "package": "haystack.core.pipeline.pipeline",
38
+ "object": "Pipeline",
39
+ "method": "run",
40
+ "wrapper_method": task_wrapper,
41
+ "span_type": "workflow"
42
+ }
43
+ ]
@@ -0,0 +1,127 @@
1
+ """
2
+ This module provides utility functions for extracting system, user,
3
+ and assistant messages from various input formats.
4
+ """
5
+
6
+ import logging
7
+ from monocle_apptrace.instrumentation.common.utils import (
8
+ Option,
9
+ get_keys_as_tuple,
10
+ get_nested_value,
11
+ try_option,
12
+ )
13
+
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ def extract_messages(args):
19
+ """Extract system and user messages"""
20
+ try:
21
+ messages = []
22
+ if args and isinstance(args, (list, tuple)) and hasattr(args[0], 'text'):
23
+ return [args[0].text]
24
+ if args and isinstance(args, (list, tuple)) and len(args) > 0:
25
+ if isinstance(args[0], list) and len(args[0]) > 0:
26
+ first_msg = args[0][0]
27
+ if hasattr(first_msg, 'content') and hasattr(first_msg, 'type') and first_msg.type == "human":
28
+ return args[0][0].content
29
+ if hasattr(args[0], "messages") and isinstance(args[0].messages, list):
30
+ for msg in args[0].messages:
31
+ if hasattr(msg, 'content') and hasattr(msg, 'type'):
32
+ messages.append({msg.type: msg.content})
33
+ return [str(d) for d in messages]
34
+ except Exception as e:
35
+ logger.warning("Warning: Error occurred in extract_messages: %s", str(e))
36
+ return []
37
+
38
+
39
+ def extract_assistant_message(response):
40
+ try:
41
+ if isinstance(response, str):
42
+ return [response]
43
+ if hasattr(response, "content"):
44
+ return [response.content]
45
+ if hasattr(response, "message") and hasattr(response.message, "content"):
46
+ return [response.message.content]
47
+ except Exception as e:
48
+ logger.warning("Warning: Error occurred in extract_assistant_message: %s", str(e))
49
+ return []
50
+
51
+
52
+ def extract_provider_name(instance):
53
+ provider_url: Option[str] = try_option(getattr, instance.client._client.base_url, 'host')
54
+ return provider_url.unwrap_or(None)
55
+
56
+
57
+ def extract_inference_endpoint(instance):
58
+ inference_endpoint: Option[str] = try_option(getattr, instance.client._client, 'base_url').map(str)
59
+ if inference_endpoint.is_none() and "meta" in instance.client.__dict__:
60
+ inference_endpoint = try_option(getattr, instance.client.meta, 'endpoint_url').map(str)
61
+
62
+ return inference_endpoint.unwrap_or(extract_provider_name(instance))
63
+
64
+
65
+ def extract_vectorstore_deployment(my_map):
66
+ if isinstance(my_map, dict):
67
+ if '_client_settings' in my_map:
68
+ client = my_map['_client_settings'].__dict__
69
+ host, port = get_keys_as_tuple(client, 'host', 'port')
70
+ if host:
71
+ return f"{host}:{port}" if port else host
72
+ keys_to_check = ['client', '_client']
73
+ host = __get_host_from_map(my_map, keys_to_check)
74
+ if host:
75
+ return host
76
+ else:
77
+ if hasattr(my_map, 'client') and '_endpoint' in my_map.client.__dict__:
78
+ return my_map.client.__dict__['_endpoint']
79
+ host, port = get_keys_as_tuple(my_map.__dict__, 'host', 'port')
80
+ if host:
81
+ return f"{host}:{port}" if port else host
82
+ return None
83
+
84
+ def __get_host_from_map(my_map, keys_to_check):
85
+ for key in keys_to_check:
86
+ seed_connections = get_nested_value(my_map, [key, 'transport', 'seed_connections'])
87
+ if seed_connections and 'host' in seed_connections[0].__dict__:
88
+ return seed_connections[0].__dict__['host']
89
+ return None
90
+
91
+ def resolve_from_alias(my_map, alias):
92
+ """Find a alias that is not none from list of aliases"""
93
+
94
+ for i in alias:
95
+ if i in my_map.keys():
96
+ return my_map[i]
97
+ return None
98
+
99
+
100
+ def update_input_span_events(args):
101
+ return args[0] if len(args) > 0 else ""
102
+
103
+
104
+ def update_output_span_events(results):
105
+ output_arg_text = " ".join([doc.page_content for doc in results if hasattr(doc, 'page_content')])
106
+ if len(output_arg_text) > 100:
107
+ output_arg_text = output_arg_text[:100] + "..."
108
+ return output_arg_text
109
+
110
+
111
+ def update_span_from_llm_response(response, instance):
112
+ meta_dict = {}
113
+ if response is not None and hasattr(response, "response_metadata"):
114
+ if hasattr(response, "usage_metadata") and response.usage_metadata is not None:
115
+ token_usage = response.usage_metadata
116
+ else:
117
+ response_metadata = response.response_metadata
118
+ token_usage = response_metadata.get("token_usage")
119
+ if token_usage is not None:
120
+ temperature = instance.__dict__.get("temperature", None)
121
+ meta_dict.update({"temperature": temperature})
122
+ meta_dict.update(
123
+ {"completion_tokens": token_usage.get("completion_tokens") or token_usage.get("output_tokens")})
124
+ meta_dict.update({"prompt_tokens": token_usage.get("prompt_tokens") or token_usage.get("input_tokens")})
125
+ meta_dict.update({"total_tokens": token_usage.get("total_tokens")})
126
+ return meta_dict
127
+
@@ -0,0 +1,72 @@
1
+ from monocle_apptrace.instrumentation.metamodel.langchain import (
2
+ _helper,
3
+ )
4
+ from monocle_apptrace.instrumentation.common.utils import resolve_from_alias, get_llm_type
5
+
6
+ INFERENCE = {
7
+ "type": "inference",
8
+ "attributes": [
9
+ [
10
+ {
11
+ "_comment": "provider type ,name , deployment , inference_endpoint",
12
+ "attribute": "type",
13
+ "accessor": lambda arguments: 'inference.' + (get_llm_type(arguments['instance']) or 'generic')
14
+
15
+ },
16
+ {
17
+ "attribute": "provider_name",
18
+ "accessor": lambda arguments: _helper.extract_provider_name(arguments['instance'])
19
+ },
20
+ {
21
+ "attribute": "deployment",
22
+ "accessor": lambda arguments: resolve_from_alias(arguments['instance'].__dict__, ['engine', 'azure_deployment', 'deployment_name', 'deployment_id', 'deployment'])
23
+ },
24
+ {
25
+ "attribute": "inference_endpoint",
26
+ "accessor": lambda arguments: resolve_from_alias(arguments['instance'].__dict__, ['azure_endpoint', 'api_base', 'endpoint']) or _helper.extract_inference_endpoint(arguments['instance'])
27
+ }
28
+ ],
29
+ [
30
+ {
31
+ "_comment": "LLM Model",
32
+ "attribute": "name",
33
+ "accessor": lambda arguments: resolve_from_alias(arguments['instance'].__dict__, ['model', 'model_name', 'endpoint_name', 'deployment_name'])
34
+ },
35
+ {
36
+ "attribute": "type",
37
+ "accessor": lambda arguments: 'model.llm.' + resolve_from_alias(arguments['instance'].__dict__, ['model', 'model_name', 'endpoint_name', 'deployment_name'])
38
+ }
39
+ ]
40
+ ],
41
+ "events": [
42
+ {"name": "data.input",
43
+ "attributes": [
44
+
45
+ {
46
+ "_comment": "this is instruction and user query to LLM",
47
+ "attribute": "input",
48
+ "accessor": lambda arguments: _helper.extract_messages(arguments['args'])
49
+ }
50
+ ]
51
+ },
52
+ {
53
+ "name": "data.output",
54
+ "attributes": [
55
+ {
56
+ "_comment": "this is result from LLM",
57
+ "attribute": "response",
58
+ "accessor": lambda arguments: _helper.extract_assistant_message(arguments['result'])
59
+ }
60
+ ]
61
+ },
62
+ {
63
+ "name": "metadata",
64
+ "attributes": [
65
+ {
66
+ "_comment": "this is metadata usage from LLM",
67
+ "accessor": lambda arguments: _helper.update_span_from_llm_response(arguments['result'], arguments['instance'])
68
+ }
69
+ ]
70
+ }
71
+ ]
72
+ }
@@ -0,0 +1,58 @@
1
+ from monocle_apptrace.instrumentation.metamodel.langchain import (
2
+ _helper,
3
+ )
4
+
5
+ RETRIEVAL = {
6
+ "type": "retrieval",
7
+ "attributes": [
8
+ [
9
+ {
10
+ "_comment": "vector store name and type",
11
+ "attribute": "name",
12
+ "accessor": lambda arguments: type(arguments['instance'].vectorstore).__name__
13
+ },
14
+ {
15
+ "attribute": "type",
16
+ "accessor": lambda arguments: 'vectorstore.' + type(arguments['instance'].vectorstore).__name__
17
+ },
18
+ {
19
+ "attribute": "deployment",
20
+ "accessor": lambda arguments: _helper.extract_vectorstore_deployment(
21
+ arguments['instance'].vectorstore.__dict__)
22
+ }
23
+ ],
24
+ [
25
+ {
26
+ "_comment": "embedding model name and type",
27
+ "attribute": "name",
28
+ "accessor": lambda arguments: _helper.resolve_from_alias(arguments['instance'].vectorstore.embeddings.__dict__,['endpoint_name','model_id','model'])
29
+ },
30
+ {
31
+ "attribute": "type",
32
+ "accessor": lambda arguments: 'model.embedding.' + _helper.resolve_from_alias(arguments['instance'].vectorstore.embeddings.__dict__,['endpoint_name','model_id','model'])
33
+ }
34
+ ]
35
+ ],
36
+ "events": [
37
+ {"name": "data.input",
38
+ "attributes": [
39
+
40
+ {
41
+ "_comment": "this is instruction and user query to LLM",
42
+ "attribute": "input",
43
+ "accessor": lambda arguments: _helper.update_input_span_events(arguments['args'])
44
+ }
45
+ ]
46
+ },
47
+ {
48
+ "name": "data.output",
49
+ "attributes": [
50
+ {
51
+ "_comment": "this is result from LLM",
52
+ "attribute": "response",
53
+ "accessor": lambda arguments: _helper.update_output_span_events(arguments['result'])
54
+ }
55
+ ]
56
+ }
57
+ ]
58
+ }