langtrace-python-sdk 2.3.22__py3-none-any.whl → 2.3.28__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
@@ -5,16 +5,24 @@ from wrapt import wrap_function_wrapper as _W
5
5
  from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
6
6
  from opentelemetry.trace import get_tracer
7
7
  from .patch import patch_vertexai
8
+ from langtrace_python_sdk.utils import is_package_installed
8
9
 
9
10
 
10
11
  class VertexAIInstrumentation(BaseInstrumentor):
11
12
  def instrumentation_dependencies(self) -> Collection[str]:
13
+ if is_package_installed("vertexai"):
14
+ return ["vertexai >= 1.0.0"]
15
+
12
16
  return ["google-cloud-aiplatform >= 1.0.0"]
13
17
 
14
18
  def _instrument(self, **kwargs):
15
19
  trace_provider = kwargs.get("tracer_provider")
16
20
  tracer = get_tracer(__name__, "", trace_provider)
17
- version = v("google-cloud-aiplatform")
21
+ version = (
22
+ v("vertexai")
23
+ if is_package_installed("vertexai")
24
+ else v("google-cloud-aiplatform")
25
+ )
18
26
 
19
27
  for _, api_config in APIS.items():
20
28
 
@@ -103,27 +103,24 @@ def is_streaming_response(response):
103
103
 
104
104
  def get_llm_model(instance):
105
105
  if hasattr(instance, "_model_name"):
106
- return instance._model_name.replace("models/", "")
106
+ return instance._model_name.replace("publishers/google/models/", "")
107
107
  return getattr(instance, "_model_id", "unknown")
108
108
 
109
109
 
110
110
  def serialize_prompts(args, kwargs):
111
- prompt = ""
112
- if args is not None and len(args) > 0:
111
+ if args and len(args) > 0:
112
+ prompt_parts = []
113
113
  for arg in args:
114
114
  if isinstance(arg, str):
115
- prompt = f"{prompt}{arg}\n"
115
+ prompt_parts.append(arg)
116
116
  elif isinstance(arg, list):
117
117
  for subarg in arg:
118
118
  if type(subarg).__name__ == "Part":
119
- prompt = f"{prompt}{json.dumps(subarg.to_dict())}\n"
119
+ prompt_parts.append(json.dumps(subarg.to_dict()))
120
120
  else:
121
- prompt = f"{prompt}{subarg}\n"
121
+ prompt_parts.append(str(subarg))
122
+
123
+ return [{"role": "user", "content": "\n".join(prompt_parts)}]
122
124
  else:
123
- prompt = [
124
- {
125
- "role": "user",
126
- "content": kwargs.get("prompt") or kwargs.get("message"),
127
- }
128
- ]
129
- return prompt
125
+ content = kwargs.get("prompt") or kwargs.get("message")
126
+ return [{"role": "user", "content": content}] if content else []
@@ -52,10 +52,6 @@ class WeaviateInstrumentation(BaseInstrumentor):
52
52
  generic_query_patch(api_name, version, tracer),
53
53
  )
54
54
  elif api_config.get("OPERATION") == "create":
55
- print(
56
- api_config["MODULE"],
57
- api_config["METHOD"],
58
- )
59
55
  wrap_function_wrapper(
60
56
  api_config["MODULE"],
61
57
  api_config["METHOD"],
@@ -16,7 +16,9 @@ limitations under the License.
16
16
 
17
17
  import os
18
18
  import sys
19
- from typing import Any, Optional
19
+ import sentry_sdk
20
+ import logging
21
+ from typing import Dict, Optional, Any
20
22
  from colorama import Fore
21
23
  from langtrace_python_sdk.constants import LANGTRACE_SDK_NAME, SENTRY_DSN
22
24
  from opentelemetry import trace
@@ -57,11 +59,7 @@ from langtrace_python_sdk.instrumentation import (
57
59
  VertexAIInstrumentation,
58
60
  WeaviateInstrumentation,
59
61
  )
60
- from langtrace_python_sdk.types import (
61
- DisableInstrumentations,
62
- InstrumentationMethods,
63
- InstrumentationType,
64
- )
62
+ from langtrace_python_sdk.types import DisableInstrumentations, InstrumentationMethods
65
63
  from langtrace_python_sdk.utils import (
66
64
  check_if_sdk_is_outdated,
67
65
  get_sdk_version,
@@ -69,62 +67,143 @@ from langtrace_python_sdk.utils import (
69
67
  validate_instrumentations,
70
68
  )
71
69
  from langtrace_python_sdk.utils.langtrace_sampler import LangtraceSampler
72
- import sentry_sdk
73
70
  from sentry_sdk.types import Event, Hint
74
71
 
72
+ logging.disable(level=logging.INFO)
73
+
74
+
75
+ class LangtraceConfig:
76
+ def __init__(self, **kwargs):
77
+ self.api_key = kwargs.get("api_key")
78
+ self.batch = kwargs.get("batch", True)
79
+ self.write_spans_to_console = kwargs.get("write_spans_to_console", False)
80
+ self.custom_remote_exporter = kwargs.get("custom_remote_exporter")
81
+ self.api_host = kwargs.get("api_host", LANGTRACE_REMOTE_URL)
82
+ self.disable_instrumentations = kwargs.get("disable_instrumentations")
83
+ self.disable_tracing_for_functions = kwargs.get("disable_tracing_for_functions")
84
+ self.service_name = kwargs.get("service_name")
85
+ self.disable_logging = kwargs.get("disable_logging", False)
86
+ self.headers = kwargs.get("headers", {})
87
+
88
+
89
+ def get_host(config: LangtraceConfig) -> str:
90
+ return (
91
+ os.environ.get("LANGTRACE_API_HOST")
92
+ or os.environ.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT")
93
+ or os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")
94
+ or config.api_host
95
+ or LANGTRACE_REMOTE_URL
96
+ )
97
+
98
+
99
+ def setup_tracer_provider(config: LangtraceConfig, host: str) -> TracerProvider:
100
+ sampler = LangtraceSampler(disabled_methods=config.disable_tracing_for_functions)
101
+ resource = Resource.create(
102
+ attributes={
103
+ SERVICE_NAME: os.environ.get("OTEL_SERVICE_NAME")
104
+ or config.service_name
105
+ or sys.argv[0]
106
+ }
107
+ )
108
+ return TracerProvider(resource=resource, sampler=sampler)
109
+
110
+
111
+ def get_exporter(config: LangtraceConfig, host: str):
112
+ if config.custom_remote_exporter:
113
+ return config.custom_remote_exporter
114
+
115
+ return LangTraceExporter(host, config.api_key, config.disable_logging)
116
+
117
+
118
+ def add_span_processor(provider: TracerProvider, config: LangtraceConfig, exporter):
119
+ if config.write_spans_to_console:
120
+ provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
121
+ print(Fore.BLUE + "Writing spans to console" + Fore.RESET)
122
+
123
+ elif config.custom_remote_exporter or get_host(config) != LANGTRACE_REMOTE_URL:
124
+ processor = (
125
+ BatchSpanProcessor(exporter)
126
+ if config.batch
127
+ else SimpleSpanProcessor(exporter)
128
+ )
129
+ provider.add_span_processor(processor)
130
+ print(
131
+ Fore.BLUE
132
+ + f"Exporting spans to custom host: {get_host(config)}.."
133
+ + Fore.RESET
134
+ )
135
+ else:
136
+ provider.add_span_processor(BatchSpanProcessor(exporter))
137
+ print(Fore.BLUE + "Exporting spans to Langtrace cloud.." + Fore.RESET)
138
+
139
+
140
+ def init_sentry(config: LangtraceConfig, host: str):
141
+ if os.environ.get("LANGTRACE_ERROR_REPORTING", "True") == "True":
142
+ sentry_sdk.init(
143
+ dsn=SENTRY_DSN,
144
+ traces_sample_rate=1.0,
145
+ profiles_sample_rate=1.0,
146
+ before_send=before_send,
147
+ )
148
+ sdk_options = {
149
+ "service_name": os.environ.get("OTEL_SERVICE_NAME")
150
+ or config.service_name
151
+ or sys.argv[0],
152
+ "disable_logging": config.disable_logging,
153
+ "disable_instrumentations": config.disable_instrumentations,
154
+ "disable_tracing_for_functions": config.disable_tracing_for_functions,
155
+ "batch": config.batch,
156
+ "write_spans_to_console": config.write_spans_to_console,
157
+ "custom_remote_exporter": config.custom_remote_exporter,
158
+ "sdk_name": LANGTRACE_SDK_NAME,
159
+ "sdk_version": get_sdk_version(),
160
+ "api_host": host,
161
+ }
162
+ sentry_sdk.set_context("sdk_init_options", sdk_options)
163
+
75
164
 
76
165
  def init(
77
- api_key: str = None,
166
+ api_key: Optional[str] = None,
78
167
  batch: bool = True,
79
168
  write_spans_to_console: bool = False,
80
- custom_remote_exporter=None,
169
+ custom_remote_exporter: Optional[Any] = None,
81
170
  api_host: Optional[str] = LANGTRACE_REMOTE_URL,
82
171
  disable_instrumentations: Optional[DisableInstrumentations] = None,
83
172
  disable_tracing_for_functions: Optional[InstrumentationMethods] = None,
84
173
  service_name: Optional[str] = None,
85
- disable_logging=False,
174
+ disable_logging: bool = False,
175
+ headers: Dict[str, str] = {},
86
176
  ):
87
- if disable_logging:
177
+ logging.disable(level=logging.INFO)
178
+ check_if_sdk_is_outdated()
179
+ config = LangtraceConfig(
180
+ api_key=api_key,
181
+ batch=batch,
182
+ write_spans_to_console=write_spans_to_console,
183
+ custom_remote_exporter=custom_remote_exporter,
184
+ api_host=api_host,
185
+ disable_instrumentations=disable_instrumentations,
186
+ disable_tracing_for_functions=disable_tracing_for_functions,
187
+ service_name=service_name,
188
+ disable_logging=disable_logging,
189
+ headers=headers,
190
+ )
191
+
192
+ if config.disable_logging:
88
193
  sys.stdout = open(os.devnull, "w")
89
194
 
90
- host = (
91
- os.environ.get("LANGTRACE_API_HOST", None)
92
- or os.environ.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", None)
93
- or os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", None)
94
- or api_host
95
- or LANGTRACE_REMOTE_URL
96
- )
97
- check_if_sdk_is_outdated()
195
+ host = get_host(config)
98
196
  print(Fore.GREEN + "Initializing Langtrace SDK.." + Fore.RESET)
99
197
  print(
100
198
  Fore.WHITE
101
199
  + "⭐ Leave our github a star to stay on top of our updates - https://github.com/Scale3-Labs/langtrace"
102
200
  + Fore.RESET
103
201
  )
104
- sampler = LangtraceSampler(disabled_methods=disable_tracing_for_functions)
105
- resource = Resource.create(
106
- attributes={
107
- SERVICE_NAME: os.environ.get("OTEL_SERVICE_NAME")
108
- or service_name
109
- or sys.argv[0]
110
- }
111
- )
112
- provider = TracerProvider(resource=resource, sampler=sampler)
113
202
 
114
- remote_write_exporter = (
115
- LangTraceExporter(
116
- api_key=api_key, api_host=host, disable_logging=disable_logging
117
- )
118
- if custom_remote_exporter is None
119
- else custom_remote_exporter
120
- )
121
- console_exporter = ConsoleSpanExporter()
122
- batch_processor_remote = BatchSpanProcessor(remote_write_exporter)
123
- simple_processor_remote = SimpleSpanProcessor(remote_write_exporter)
124
- simple_processor_console = SimpleSpanProcessor(console_exporter)
203
+ provider = setup_tracer_provider(config, host)
204
+ exporter = get_exporter(config, host)
125
205
 
126
206
  os.environ["LANGTRACE_API_HOST"] = host.replace("/api/trace", "")
127
- # Initialize tracer
128
207
  trace.set_tracer_provider(provider)
129
208
  all_instrumentations = {
130
209
  "openai": OpenAIInstrumentation(),
@@ -146,57 +225,18 @@ def init(
146
225
  "ollama": OllamaInstrumentor(),
147
226
  "dspy-ai": DspyInstrumentation(),
148
227
  "crewai": CrewAIInstrumentation(),
228
+ "vertexai": VertexAIInstrumentation(),
149
229
  "google-cloud-aiplatform": VertexAIInstrumentation(),
150
230
  "google-generativeai": GeminiInstrumentation(),
151
231
  "mistralai": MistralInstrumentation(),
152
232
  "autogen": AutogenInstrumentation(),
153
233
  }
154
234
 
155
- init_instrumentations(disable_instrumentations, all_instrumentations)
156
- if write_spans_to_console:
157
- print(Fore.BLUE + "Writing spans to console" + Fore.RESET)
158
- provider.add_span_processor(simple_processor_console)
159
-
160
- elif custom_remote_exporter is not None:
161
- print(Fore.BLUE + "Exporting spans to custom remote exporter.." + Fore.RESET)
162
- if batch:
163
- provider.add_span_processor(batch_processor_remote)
164
- else:
165
- provider.add_span_processor(simple_processor_remote)
166
-
167
- elif host != LANGTRACE_REMOTE_URL:
168
- print(Fore.BLUE + f"Exporting spans to custom host: {host}.." + Fore.RESET)
169
- if batch:
170
- provider.add_span_processor(batch_processor_remote)
171
- else:
172
- provider.add_span_processor(simple_processor_remote)
173
- else:
174
- print(Fore.BLUE + "Exporting spans to Langtrace cloud.." + Fore.RESET)
175
- provider.add_span_processor(batch_processor_remote)
235
+ init_instrumentations(config.disable_instrumentations, all_instrumentations)
236
+ add_span_processor(provider, config, exporter)
176
237
 
177
238
  sys.stdout = sys.__stdout__
178
- if os.environ.get("LANGTRACE_ERROR_REPORTING", "True") == "True":
179
- sentry_sdk.init(
180
- dsn=SENTRY_DSN,
181
- traces_sample_rate=1.0,
182
- profiles_sample_rate=1.0,
183
- before_send=before_send,
184
- )
185
- sdk_options = {
186
- "service_name": os.environ.get("OTEL_SERVICE_NAME")
187
- or service_name
188
- or sys.argv[0],
189
- "disable_logging": disable_logging,
190
- "disable_instrumentations": disable_instrumentations,
191
- "disable_tracing_for_functions": disable_tracing_for_functions,
192
- "batch": batch,
193
- "write_spans_to_console": write_spans_to_console,
194
- "custom_remote_exporter": custom_remote_exporter,
195
- "sdk_name": LANGTRACE_SDK_NAME,
196
- "sdk_version": get_sdk_version(),
197
- "api_host": host,
198
- }
199
- sentry_sdk.set_context("sdk_init_options", sdk_options)
239
+ init_sentry(config, host)
200
240
 
201
241
 
202
242
  def before_send(event: Event, hint: Hint):
@@ -222,7 +262,10 @@ def init_instrumentations(
222
262
  if disable_instrumentations is None:
223
263
  for name, v in all_instrumentations.items():
224
264
  if is_package_installed(name):
225
- v.instrument()
265
+ try:
266
+ v.instrument()
267
+ except Exception as e:
268
+ print(f"Skipping {name} due to error while instrumenting: {e}")
226
269
 
227
270
  else:
228
271
 
@@ -244,4 +287,7 @@ def init_instrumentations(
244
287
 
245
288
  for name, v in filtered_dict.items():
246
289
  if is_package_installed(name):
247
- v.instrument()
290
+ try:
291
+ v.instrument()
292
+ except Exception as e:
293
+ print(f"Skipping {name} due to error while instrumenting: {e}")
@@ -1 +1 @@
1
- __version__ = "2.3.22"
1
+ __version__ = "2.3.28"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: langtrace-python-sdk
3
- Version: 2.3.22
3
+ Version: 2.3.28
4
4
  Summary: Python SDK for LangTrace
5
5
  Project-URL: Homepage, https://github.com/Scale3-Labs/langtrace-python-sdk
6
6
  Author-email: Scale3 Labs <engineering@scale3labs.com>
@@ -35,10 +35,10 @@ Requires-Dist: groq; extra == 'dev'
35
35
  Requires-Dist: langchain; extra == 'dev'
36
36
  Requires-Dist: langchain-community; extra == 'dev'
37
37
  Requires-Dist: langchain-openai; extra == 'dev'
38
- Requires-Dist: litellm; extra == 'dev'
38
+ Requires-Dist: litellm==1.48.7; extra == 'dev'
39
39
  Requires-Dist: mistralai; extra == 'dev'
40
40
  Requires-Dist: ollama; extra == 'dev'
41
- Requires-Dist: openai==1.30.1; extra == 'dev'
41
+ Requires-Dist: openai==1.45.0; extra == 'dev'
42
42
  Requires-Dist: pinecone-client; extra == 'dev'
43
43
  Requires-Dist: python-dotenv; extra == 'dev'
44
44
  Requires-Dist: qdrant-client; extra == 'dev'
@@ -96,8 +96,8 @@ examples/vertexai_example/main.py,sha256=gndId5X5ksD-ycxnAWMdEqIDbLc3kz5Vt8vm4YP
96
96
  examples/weaviate_example/__init__.py,sha256=8JMDBsRSEV10HfTd-YC7xb4txBjD3la56snk-Bbg2Kw,618
97
97
  examples/weaviate_example/query_text.py,sha256=wPHQTc_58kPoKTZMygVjTj-2ZcdrIuaausJfMxNQnQc,127162
98
98
  langtrace_python_sdk/__init__.py,sha256=VZM6i71NR7pBQK6XvJWRelknuTYUhqwqE7PlicKa5Wg,1166
99
- langtrace_python_sdk/langtrace.py,sha256=YJUHbxNjhtlQvTbkmN-tqmGiKp3Yog70KR7GVlhIr7c,8936
100
- langtrace_python_sdk/version.py,sha256=t_d6fGpbp-4uYw6IIW6eCTz39jbZes5f7hJjns8ZIZk,23
99
+ langtrace_python_sdk/langtrace.py,sha256=EIj2oQc2b_Vsm0bKqriYcnJHXxJbMmTu3rCUm25E5_s,10692
100
+ langtrace_python_sdk/version.py,sha256=ImBYwB7j6gYW6C4wQspgV1X6VBv-lPBjWsjd6lJOmlo,23
101
101
  langtrace_python_sdk/constants/__init__.py,sha256=3CNYkWMdd1DrkGqzLUgNZXjdAlM6UFMlf_F-odAToyc,146
102
102
  langtrace_python_sdk/constants/exporter/langtrace_exporter.py,sha256=5MNjnAOg-4am78J3gVMH6FSwq5N8TOj72ugkhsw4vi0,46
103
103
  langtrace_python_sdk/constants/instrumentation/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -184,10 +184,10 @@ langtrace_python_sdk/instrumentation/qdrant/__init__.py,sha256=TaIGSAEPysrL23KJ5
184
184
  langtrace_python_sdk/instrumentation/qdrant/instrumentation.py,sha256=vl2eKSP55aqDo1JiRlvOUBrr6kddvG9Z5dCYew2OG08,1816
185
185
  langtrace_python_sdk/instrumentation/qdrant/patch.py,sha256=IgdozFyKqB8n72BjKvBDiMhYM4o75DReD0I8_uIQ7KY,5015
186
186
  langtrace_python_sdk/instrumentation/vertexai/__init__.py,sha256=ZzKxB7bl0FaRlgJhhgAk5V8Bf20FmThWM_Z9u9Eyy1s,92
187
- langtrace_python_sdk/instrumentation/vertexai/instrumentation.py,sha256=Keeb1D7nJDYu33w6H8Q8jLS7OOJtSIHqngvJMipWqJo,1143
188
- langtrace_python_sdk/instrumentation/vertexai/patch.py,sha256=vPxwuSKgA3cUtelgot4XZEox8AD4ehsi3bNTKD_HS_M,4394
187
+ langtrace_python_sdk/instrumentation/vertexai/instrumentation.py,sha256=yz4trw0BqGbNUvlagsejk_j8pDvRHxxQFtYJVarNKqY,1393
188
+ langtrace_python_sdk/instrumentation/vertexai/patch.py,sha256=mLMmmmovYBaDXgnSSJEt3iwv5xBLJv1XZHxW_xRVeXo,4433
189
189
  langtrace_python_sdk/instrumentation/weaviate/__init__.py,sha256=Mc-Je6evPo-kKQzerTG7bd1XO5JOh4YGTE3wBxaUBwg,99
190
- langtrace_python_sdk/instrumentation/weaviate/instrumentation.py,sha256=ow081UHPLZqsmMrVjbzNoZ0tU2JComhTCz_x1xhdWTU,2558
190
+ langtrace_python_sdk/instrumentation/weaviate/instrumentation.py,sha256=Kwq5QQTUQNRHrWrMnNe9X0TcqtXGiNpBidsuToRTqG0,2417
191
191
  langtrace_python_sdk/instrumentation/weaviate/patch.py,sha256=aWLDbNGz35V6XQUv4lkMD0O689suqh6KdTa33VDtUkE,6905
192
192
  langtrace_python_sdk/types/__init__.py,sha256=VnfLV5pVHIB9VRIpEwIDQjWSPEAqQKnq6VNbqsm9W3Q,4287
193
193
  langtrace_python_sdk/utils/__init__.py,sha256=O-Ra9IDd1MnxihdQUC8HW_wYFhk7KbTCK2BIl02yacQ,2935
@@ -241,8 +241,8 @@ tests/pinecone/cassettes/test_query.yaml,sha256=b5v9G3ssUy00oG63PlFUR3JErF2Js-5A
241
241
  tests/pinecone/cassettes/test_upsert.yaml,sha256=neWmQ1v3d03V8WoLl8FoFeeCYImb8pxlJBWnFd_lITU,38607
242
242
  tests/qdrant/conftest.py,sha256=9n0uHxxIjWk9fbYc4bx-uP8lSAgLBVx-cV9UjnsyCHM,381
243
243
  tests/qdrant/test_qdrant.py,sha256=pzjAjVY2kmsmGfrI2Gs2xrolfuaNHz7l1fqGQCjp5_o,3353
244
- langtrace_python_sdk-2.3.22.dist-info/METADATA,sha256=nVVecbmqTGT_8puoT55JzFEOe2zT9TI-9HJ9Eqd5S7U,15861
245
- langtrace_python_sdk-2.3.22.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
246
- langtrace_python_sdk-2.3.22.dist-info/entry_points.txt,sha256=1_b9-qvf2fE7uQNZcbUei9vLpFZBbbh9LrtGw95ssAo,70
247
- langtrace_python_sdk-2.3.22.dist-info/licenses/LICENSE,sha256=QwcOLU5TJoTeUhuIXzhdCEEDDvorGiC6-3YTOl4TecE,11356
248
- langtrace_python_sdk-2.3.22.dist-info/RECORD,,
244
+ langtrace_python_sdk-2.3.28.dist-info/METADATA,sha256=P-q84MJ5U97nouGja8E9xrhjgL1D2X9t6oC6IWIW9zw,15869
245
+ langtrace_python_sdk-2.3.28.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
246
+ langtrace_python_sdk-2.3.28.dist-info/entry_points.txt,sha256=1_b9-qvf2fE7uQNZcbUei9vLpFZBbbh9LrtGw95ssAo,70
247
+ langtrace_python_sdk-2.3.28.dist-info/licenses/LICENSE,sha256=QwcOLU5TJoTeUhuIXzhdCEEDDvorGiC6-3YTOl4TecE,11356
248
+ langtrace_python_sdk-2.3.28.dist-info/RECORD,,