|
| 1 | +from typing import Any, Dict |
| 2 | +from opentelemetry.trace import SpanKind |
| 3 | +from opentelemetry.instrumentation.utils import unwrap |
| 4 | +from wrapt import wrap_function_wrapper |
| 5 | + |
| 6 | +from agentops.instrumentation.common import ( |
| 7 | + CommonInstrumentor, |
| 8 | + InstrumentorConfig, |
| 9 | + StandardMetrics, |
| 10 | + create_wrapper_factory, |
| 11 | + create_span, |
| 12 | + SpanAttributeManager, |
| 13 | +) |
| 14 | +from agentops.semconv import SpanAttributes |
| 15 | + |
| 16 | + |
| 17 | +_instruments = ("haystack-ai >= 2.0.0",) |
| 18 | + |
| 19 | + |
| 20 | +class HaystackInstrumentor(CommonInstrumentor): |
| 21 | + def __init__(self): |
| 22 | + config = InstrumentorConfig( |
| 23 | + library_name="haystack", |
| 24 | + library_version="2", |
| 25 | + wrapped_methods=[], |
| 26 | + metrics_enabled=False, |
| 27 | + dependencies=_instruments, |
| 28 | + ) |
| 29 | + super().__init__(config) |
| 30 | + self._attribute_manager = None |
| 31 | + |
| 32 | + def _initialize(self, **kwargs): |
| 33 | + application_name = kwargs.get("application_name", "default_application") |
| 34 | + environment = kwargs.get("environment", "default_environment") |
| 35 | + self._attribute_manager = SpanAttributeManager(service_name=application_name, deployment_environment=environment) |
| 36 | + |
| 37 | + def _create_metrics(self, meter) -> Dict[str, Any]: |
| 38 | + return StandardMetrics.create_standard_metrics(meter) |
| 39 | + |
| 40 | + def _custom_wrap(self, **kwargs): |
| 41 | + attr_manager = self._attribute_manager |
| 42 | + |
| 43 | + wrap_function_wrapper( |
| 44 | + "haystack.components.generators.openai", |
| 45 | + "OpenAIGenerator.run", |
| 46 | + create_wrapper_factory(_wrap_haystack_run_impl, self._metrics, attr_manager)(self._tracer), |
| 47 | + ) |
| 48 | + |
| 49 | + wrap_function_wrapper( |
| 50 | + "haystack.components.generators.chat", |
| 51 | + "AzureOpenAIChatGenerator.run", |
| 52 | + create_wrapper_factory(_wrap_haystack_run_impl, self._metrics, attr_manager)(self._tracer), |
| 53 | + ) |
| 54 | + |
| 55 | + try: |
| 56 | + wrap_function_wrapper( |
| 57 | + "haystack.components.generators.openai", |
| 58 | + "OpenAIGenerator.stream", |
| 59 | + create_wrapper_factory(_wrap_haystack_stream_impl, self._metrics, attr_manager)(self._tracer), |
| 60 | + ) |
| 61 | + except Exception: |
| 62 | + pass |
| 63 | + |
| 64 | + try: |
| 65 | + wrap_function_wrapper( |
| 66 | + "haystack.components.generators.chat", |
| 67 | + "AzureOpenAIChatGenerator.stream", |
| 68 | + create_wrapper_factory(_wrap_haystack_stream_impl, self._metrics, attr_manager)(self._tracer), |
| 69 | + ) |
| 70 | + except Exception: |
| 71 | + pass |
| 72 | + |
| 73 | + def _custom_unwrap(self, **kwargs): |
| 74 | + unwrap("haystack.components.generators.openai", "OpenAIGenerator.run") |
| 75 | + unwrap("haystack.components.generators.chat", "AzureOpenAIChatGenerator.run") |
| 76 | + try: |
| 77 | + unwrap("haystack.components.generators.openai", "OpenAIGenerator.stream") |
| 78 | + except Exception: |
| 79 | + pass |
| 80 | + try: |
| 81 | + unwrap("haystack.components.generators.chat", "AzureOpenAIChatGenerator.stream") |
| 82 | + except Exception: |
| 83 | + pass |
| 84 | + |
| 85 | + |
| 86 | +def _first_non_empty_text(value): |
| 87 | + if isinstance(value, list) and value: |
| 88 | + return _first_non_empty_text(value[0]) |
| 89 | + if isinstance(value, dict): |
| 90 | + if "content" in value: |
| 91 | + return str(value["content"]) |
| 92 | + if "text" in value: |
| 93 | + return str(value["text"]) |
| 94 | + if "replies" in value and value["replies"]: |
| 95 | + return str(value["replies"][0]) |
| 96 | + if value is None: |
| 97 | + return None |
| 98 | + return str(value) |
| 99 | + |
| 100 | + |
| 101 | +def _extract_prompt(args, kwargs): |
| 102 | + if "prompt" in kwargs: |
| 103 | + return kwargs.get("prompt") |
| 104 | + if "messages" in kwargs: |
| 105 | + return kwargs.get("messages") |
| 106 | + if args: |
| 107 | + return args[0] |
| 108 | + return None |
| 109 | + |
| 110 | + |
| 111 | +def _get_model_name(instance): |
| 112 | + for attr in ("model", "model_name", "deployment_name", "deployment"): |
| 113 | + if hasattr(instance, attr): |
| 114 | + val = getattr(instance, attr) |
| 115 | + if val: |
| 116 | + return str(val) |
| 117 | + return None |
| 118 | + |
| 119 | + |
| 120 | +def _wrap_haystack_run_impl(tracer, metrics, attr_manager, wrapped, instance, args, kwargs): |
| 121 | + model = _get_model_name(instance) |
| 122 | + with create_span( |
| 123 | + tracer, |
| 124 | + "haystack.generator.run", |
| 125 | + kind=SpanKind.CLIENT, |
| 126 | + attributes={SpanAttributes.LLM_SYSTEM: "haystack", "gen_ai.model": model, SpanAttributes.LLM_REQUEST_STREAMING: False}, |
| 127 | + attribute_manager=attr_manager, |
| 128 | + ) as span: |
| 129 | + prompt = _extract_prompt(args, kwargs) |
| 130 | + prompt_text = _first_non_empty_text(prompt) |
| 131 | + if prompt_text: |
| 132 | + span.set_attribute("gen_ai.prompt.0.content", prompt_text[:500]) |
| 133 | + |
| 134 | + result = wrapped(*args, **kwargs) |
| 135 | + |
| 136 | + reply_text = None |
| 137 | + if isinstance(result, dict): |
| 138 | + reply_text = _first_non_empty_text(result.get("replies")) |
| 139 | + if not reply_text: |
| 140 | + reply_text = _first_non_empty_text(result) |
| 141 | + else: |
| 142 | + reply_text = _first_non_empty_text(result) |
| 143 | + |
| 144 | + if reply_text: |
| 145 | + span.set_attribute("gen_ai.response.0.content", str(reply_text)[:500]) |
| 146 | + |
| 147 | + return result |
| 148 | + |
| 149 | + |
| 150 | +def _wrap_haystack_stream_impl(tracer, metrics, attr_manager, wrapped, instance, args, kwargs): |
| 151 | + model = _get_model_name(instance) |
| 152 | + with create_span( |
| 153 | + tracer, |
| 154 | + "haystack.generator.stream", |
| 155 | + kind=SpanKind.CLIENT, |
| 156 | + attributes={SpanAttributes.LLM_SYSTEM: "haystack", "gen_ai.model": model, SpanAttributes.LLM_REQUEST_STREAMING: True}, |
| 157 | + attribute_manager=attr_manager, |
| 158 | + ) as span: |
| 159 | + prompt = _extract_prompt(args, kwargs) |
| 160 | + prompt_text = _first_non_empty_text(prompt) |
| 161 | + if prompt_text: |
| 162 | + span.set_attribute("gen_ai.prompt.0.content", prompt_text[:500]) |
| 163 | + |
| 164 | + out = wrapped(*args, **kwargs) |
| 165 | + |
| 166 | + try: |
| 167 | + chunk_count = 0 |
| 168 | + for chunk in out: |
| 169 | + chunk_count += 1 |
| 170 | + last_text = _first_non_empty_text(chunk) |
| 171 | + if last_text: |
| 172 | + span.set_attribute("gen_ai.response.0.content", str(last_text)[:500]) |
| 173 | + yield chunk |
| 174 | + span.set_attribute("gen_ai.response.chunk_count", chunk_count) |
| 175 | + except TypeError: |
| 176 | + return out |
0 commit comments