Skip to content

Commit ad44fa3

Browse files
committed
Merge branch 'main' of github.com:Scale3-Labs/langtrace-python-sdk into release
2 parents 508e72b + c024295 commit ad44fa3

File tree

24 files changed

+241
-81
lines changed

24 files changed

+241
-81
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import json
2+
from typing import Dict
3+
4+
import boto3
5+
from dotenv import load_dotenv
6+
from langchain.chains.question_answering import load_qa_chain
7+
from langchain_community.llms.sagemaker_endpoint import (LLMContentHandler,
8+
SagemakerEndpoint)
9+
from langchain_core.documents import Document
10+
from langchain_core.prompts import PromptTemplate
11+
12+
from langtrace_python_sdk import langtrace, with_langtrace_root_span
13+
14+
# Add the path to the root of the project to the sys.path
15+
16+
load_dotenv()
17+
18+
langtrace.init()
19+
example_doc_1 = """
20+
Peter and Elizabeth took a taxi to attend the night party in the city. While in the party, Elizabeth collapsed and was rushed to the hospital.
21+
Since she was diagnosed with a brain injury, the doctor told Peter to stay besides her until she gets well.
22+
Therefore, Peter stayed with her at the hospital for 3 days without leaving.
23+
"""
24+
25+
docs = [
26+
Document(
27+
page_content=example_doc_1,
28+
)
29+
]
30+
31+
32+
query = """How long was Elizabeth hospitalized?"""
33+
prompt_template = """Use the following pieces of context to answer the question at the end.
34+
35+
{context}
36+
37+
Question: {question}
38+
Answer:"""
39+
PROMPT = PromptTemplate(
40+
template=prompt_template, input_variables=["context", "question"]
41+
)
42+
43+
44+
client = boto3.client(
45+
"sagemaker-runtime",
46+
region_name="us-east-1",
47+
)
48+
49+
50+
class ContentHandler(LLMContentHandler):
51+
content_type = "application/json"
52+
accepts = "application/json"
53+
54+
def transform_input(self, prompt: str, model_kwargs: Dict) -> bytes:
55+
input_str = json.dumps({"inputs": prompt, "parameters": model_kwargs})
56+
return input_str.encode("utf-8")
57+
58+
def transform_output(self, output: bytes) -> str:
59+
response_json = json.loads(output.read().decode("utf-8"))
60+
return response_json["generated_text"]
61+
62+
63+
@with_langtrace_root_span("SagemakerEndpoint")
64+
def main():
65+
content_handler = ContentHandler()
66+
67+
chain = load_qa_chain(
68+
llm=SagemakerEndpoint(
69+
endpoint_name="jumpstart-dft-meta-textgeneration-l-20240809-083223",
70+
client=client,
71+
model_kwargs={"temperature": 1e-10},
72+
content_handler=content_handler,
73+
),
74+
prompt=PROMPT,
75+
)
76+
77+
res = chain({"input_documents": docs, "question": query}, return_only_outputs=True)
78+
print(res)
79+
80+
81+
main()

src/langtrace_python_sdk/constants/instrumentation/common.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
"gpt-4-1106-preview": "cl100k_base",
66
"gpt-4-1106-vision-preview": "cl100k_base",
77
"gpt-4o": "0200k_base",
8+
"gpt-4o-mini": "0200k_base",
89
}
910

1011
SERVICE_PROVIDERS = {

src/langtrace_python_sdk/instrumentation/anthropic/patch.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
get_langtrace_attributes,
2424
get_llm_request_attributes,
2525
get_llm_url,
26+
get_span_name,
2627
is_streaming,
2728
set_event_completion,
2829
set_event_completion_chunk,
@@ -64,7 +65,7 @@ def traced_method(wrapped, instance, args, kwargs):
6465
attributes = LLMSpanAttributes(**span_attributes)
6566

6667
span = tracer.start_span(
67-
APIS["MESSAGES_CREATE"]["METHOD"], kind=SpanKind.CLIENT
68+
name=get_span_name(APIS["MESSAGES_CREATE"]["METHOD"]), kind=SpanKind.CLIENT
6869
)
6970
for field, value in attributes.model_dump(by_alias=True).items():
7071
set_span_attribute(span, field, value)

src/langtrace_python_sdk/instrumentation/chroma/patch.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
from langtrace.trace_attributes import DatabaseSpanAttributes
1818
from langtrace_python_sdk.utils import set_span_attribute
19+
from langtrace_python_sdk.utils.llm import get_span_name
1920
from langtrace_python_sdk.utils.silently_fail import silently_fail
2021
from opentelemetry import baggage, trace
2122
from opentelemetry.trace import SpanKind
@@ -60,7 +61,7 @@ def traced_method(wrapped, instance, args, kwargs):
6061
attributes = DatabaseSpanAttributes(**span_attributes)
6162

6263
with tracer.start_as_current_span(
63-
api["METHOD"],
64+
name=get_span_name(api["METHOD"]),
6465
kind=SpanKind.CLIENT,
6566
context=set_span_in_context(trace.get_current_span()),
6667
) as span:

src/langtrace_python_sdk/instrumentation/cohere/patch.py

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
get_llm_request_attributes,
2222
get_extra_attributes,
2323
get_llm_url,
24+
get_span_name,
2425
set_event_completion,
2526
set_event_completion_chunk,
2627
set_usage_attributes,
@@ -57,7 +58,9 @@ def traced_method(wrapped, instance, args, kwargs):
5758

5859
attributes = LLMSpanAttributes(**span_attributes)
5960

60-
span = tracer.start_span(APIS["RERANK"]["METHOD"], kind=SpanKind.CLIENT)
61+
span = tracer.start_span(
62+
name=get_span_name(APIS["RERANK"]["METHOD"]), kind=SpanKind.CLIENT
63+
)
6164
for field, value in attributes.model_dump(by_alias=True).items():
6265
set_span_attribute(span, field, value)
6366
try:
@@ -137,7 +140,10 @@ def traced_method(wrapped, instance, args, kwargs):
137140

138141
attributes = LLMSpanAttributes(**span_attributes)
139142

140-
span = tracer.start_span(APIS["EMBED"]["METHOD"], kind=SpanKind.CLIENT)
143+
span = tracer.start_span(
144+
name=get_span_name(APIS["EMBED"]["METHOD"]),
145+
kind=SpanKind.CLIENT,
146+
)
141147
for field, value in attributes.model_dump(by_alias=True).items():
142148
set_span_attribute(span, field, value)
143149
try:
@@ -225,7 +231,9 @@ def traced_method(wrapped, instance, args, kwargs):
225231
# stringify the list of objects
226232
attributes.llm_tool_results = json.dumps(kwargs.get("tool_results"))
227233

228-
span = tracer.start_span(APIS["CHAT_CREATE"]["METHOD"], kind=SpanKind.CLIENT)
234+
span = tracer.start_span(
235+
name=get_span_name(APIS["CHAT_CREATE"]["METHOD"]), kind=SpanKind.CLIENT
236+
)
229237

230238
# Set the attributes on the span
231239
for field, value in attributes.model_dump(by_alias=True).items():
@@ -391,7 +399,9 @@ def traced_method(wrapped, instance, args, kwargs):
391399
# stringify the list of objects
392400
attributes.llm_tool_results = json.dumps(kwargs.get("tool_results"))
393401

394-
span = tracer.start_span(APIS["CHAT_STREAM"]["METHOD"], kind=SpanKind.CLIENT)
402+
span = tracer.start_span(
403+
name=get_span_name(APIS["CHAT_STREAM"]["METHOD"]), kind=SpanKind.CLIENT
404+
)
395405
for field, value in attributes.model_dump(by_alias=True).items():
396406
set_span_attribute(span, field, value)
397407
try:

src/langtrace_python_sdk/instrumentation/crewai/patch.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from importlib_metadata import version as v
33
from langtrace_python_sdk.constants import LANGTRACE_SDK_NAME
44
from langtrace_python_sdk.utils import set_span_attribute
5+
from langtrace_python_sdk.utils.llm import get_span_name
56
from langtrace_python_sdk.utils.silently_fail import silently_fail
67
from langtrace_python_sdk.constants.instrumentation.common import (
78
LANGTRACE_ADDITIONAL_SPAN_ATTRIBUTES_KEY,
@@ -143,7 +144,9 @@ def traced_method(wrapped, instance, args, kwargs):
143144

144145
attributes = FrameworkSpanAttributes(**span_attributes)
145146

146-
with tracer.start_as_current_span(operation_name, kind=SpanKind.CLIENT) as span:
147+
with tracer.start_as_current_span(
148+
get_span_name(operation_name), kind=SpanKind.CLIENT
149+
) as span:
147150
_set_input_attributes(span, kwargs, attributes)
148151

149152
try:

src/langtrace_python_sdk/instrumentation/gemini/patch.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
get_langtrace_attributes,
1111
get_llm_request_attributes,
1212
get_llm_url,
13+
get_span_name,
1314
is_streaming,
1415
set_event_completion,
1516
set_event_completion_chunk,
@@ -35,7 +36,7 @@ def traced_method(wrapped, instance, args, kwargs):
3536
}
3637
attributes = LLMSpanAttributes(**span_attributes)
3738
span = tracer.start_span(
38-
name=name,
39+
name=get_span_name(name),
3940
kind=SpanKind.CLIENT,
4041
context=set_span_in_context(trace.get_current_span()),
4142
)
@@ -76,7 +77,7 @@ async def traced_method(wrapped, instance, args, kwargs):
7677
}
7778
attributes = LLMSpanAttributes(**span_attributes)
7879
span = tracer.start_span(
79-
name=name,
80+
name=get_span_name(name),
8081
kind=SpanKind.CLIENT,
8182
context=set_span_in_context(trace.get_current_span()),
8283
)

src/langtrace_python_sdk/instrumentation/groq/patch.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
get_llm_request_attributes,
3030
get_llm_url,
3131
get_langtrace_attributes,
32+
get_span_name,
3233
set_event_completion,
3334
set_event_completion_chunk,
3435
set_usage_attributes,
@@ -107,7 +108,7 @@ def traced_method(wrapped, instance, args, kwargs):
107108
# with tracer.start_as_current_span(APIS["CHAT_COMPLETION"]["METHOD"],
108109
# kind=SpanKind.CLIENT) as span:
109110
span = tracer.start_span(
110-
APIS["CHAT_COMPLETION"]["METHOD"],
111+
name=get_span_name(APIS["CHAT_COMPLETION"]["METHOD"]),
111112
kind=SpanKind.CLIENT,
112113
context=set_span_in_context(trace.get_current_span()),
113114
)
@@ -335,7 +336,7 @@ async def traced_method(wrapped, instance, args, kwargs):
335336
# with tracer.start_as_current_span(APIS["CHAT_COMPLETION"]["METHOD"],
336337
# kind=SpanKind.CLIENT) as span:
337338
span = tracer.start_span(
338-
APIS["CHAT_COMPLETION"]["METHOD"], kind=SpanKind.CLIENT
339+
name=get_span_name(APIS["CHAT_COMPLETION"]["METHOD"]), kind=SpanKind.CLIENT
339340
)
340341
for field, value in attributes.model_dump(by_alias=True).items():
341342
set_span_attribute(span, field, value)

src/langtrace_python_sdk/instrumentation/langchain/patch.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
from langtrace.trace_attributes import FrameworkSpanAttributes
2020
from langtrace_python_sdk.constants import LANGTRACE_SDK_NAME
21+
from langtrace_python_sdk.utils.llm import get_span_name
2122
from opentelemetry import baggage, trace
2223
from opentelemetry.trace.propagation import set_span_in_context
2324
from opentelemetry.trace import SpanKind, StatusCode
@@ -57,7 +58,7 @@ def traced_method(wrapped, instance, args, kwargs):
5758
attributes = FrameworkSpanAttributes(**span_attributes)
5859

5960
with tracer.start_as_current_span(
60-
method_name,
61+
name=get_span_name(method_name),
6162
kind=SpanKind.CLIENT,
6263
context=set_span_in_context(trace.get_current_span()),
6364
) as span:

src/langtrace_python_sdk/instrumentation/langchain_community/instrumentation.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,8 @@ def patch_module_classes(
4949
lambda member: inspect.isclass(member) and member.__module__ == module.__name__,
5050
):
5151
# loop through all public methods of the class
52-
for method_name, _ in inspect.getmembers(obj, predicate=inspect.isfunction):
53-
# Skip private methods
54-
if method_name.startswith("_"):
52+
for method_name, method in inspect.getmembers(obj, predicate=inspect.isfunction):
53+
if method.__qualname__.split('.')[0] != name:
5554
continue
5655
try:
5756
method_path = f"{name}.{method_name}"
@@ -82,6 +81,12 @@ def _instrument(self, **kwargs):
8281

8382
# List of modules to patch, with their corresponding patch names
8483
modules_to_patch = [
84+
(
85+
"langchain_community.llms.sagemaker_endpoint",
86+
"sagemaker_endpoint",
87+
True,
88+
True,
89+
),
8590
("langchain_community.document_loaders.pdf", "load_pdf", True, True),
8691
("langchain_community.vectorstores.faiss", "vector_store", False, False),
8792
("langchain_community.vectorstores.pgvector", "vector_store", False, False),

0 commit comments

Comments
 (0)