Skip to content

Commit 3897fa3

Browse files
Bugfixes to sending user feedback and consolidating env var (#261)
* ENV var bugfixes, send user feedback fixes * Slack template * Bump version
1 parent c7fe290 commit 3897fa3

File tree

6 files changed

+131
-8
lines changed

6 files changed

+131
-8
lines changed

src/examples/inspect_ai_example/basic_eval.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import fsspec
2+
from dotenv import find_dotenv, load_dotenv
23
from inspect_ai import Task, task
34
from inspect_ai.dataset import csv_dataset, Sample
45
from inspect_ai.scorer import model_graded_qa
56
from inspect_ai.solver import chain_of_thought, self_critique
67
from langtrace_python_sdk.extensions.langtrace_filesystem import LangTraceFileSystem
78

9+
_ = load_dotenv(find_dotenv())
810

911
# Manually register the filesystem with fsspec
1012
# Note: This is only necessary because the filesystem is not registered.
@@ -24,9 +26,9 @@ def hydrate_with_question(record):
2426

2527

2628
@task
27-
def pricing_question():
29+
def basic_eval():
2830
return Task(
29-
dataset=csv_dataset("langtracefs://clyythmcs0001145cuvi426zi", hydrate_with_question),
31+
dataset=csv_dataset("langtracefs://clz0p4i1t000fwv0xjtlvkxyx"),
3032
plan=[chain_of_thought(), self_critique()],
3133
scorer=model_graded_qa(),
3234
)
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from dotenv import find_dotenv, load_dotenv
2+
from openai import OpenAI
3+
from langtrace_python_sdk import langtrace, with_langtrace_root_span, SendUserFeedback
4+
5+
_ = load_dotenv(find_dotenv())
6+
7+
# Initialize Langtrace SDK
8+
langtrace.init()
9+
client = OpenAI()
10+
11+
12+
def api(span_id, trace_id):
13+
response = client.chat.completions.create(
14+
model="gpt-4o-mini",
15+
messages=[
16+
{"role": "user", "content": "What is the best place to live in the US?"},
17+
],
18+
stream=False,
19+
)
20+
21+
# Collect user feedback and send it to Langtrace
22+
user_score = 1 # Example user score
23+
user_id = 'user_1234' # Example user ID
24+
data = {
25+
"userScore": user_score,
26+
"userId": user_id,
27+
"spanId": span_id,
28+
"traceId": trace_id
29+
}
30+
SendUserFeedback().evaluate(data=data)
31+
32+
# Return the response
33+
return response.choices[0].message.content
34+
35+
36+
# wrap the API call with the Langtrace root span
37+
wrapped_api = with_langtrace_root_span()(api)
38+
39+
# Call the wrapped API
40+
wrapped_api()
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import sys
2+
3+
sys.path.insert(0, "/Users/karthikkalyanaraman/work/langtrace/langtrace-python-sdk/src")
4+
5+
from langtrace_python_sdk import langtrace
6+
from langtrace_python_sdk.utils.with_root_span import with_langtrace_root_span
7+
from routellm.controller import Controller
8+
from dotenv import load_dotenv
9+
10+
load_dotenv()
11+
12+
langtrace.init()
13+
14+
# litellm.set_verbose=True
15+
client = Controller(
16+
routers=["mf"],
17+
strong_model="claude-3-opus-20240229",
18+
weak_model="claude-3-opus-20240229",
19+
)
20+
21+
22+
@with_langtrace_root_span("Routellm")
23+
def Routellm(prompt):
24+
try:
25+
26+
response = client.chat.completions.create(
27+
model="router-mf-0.11593", messages=[{"role": "user", "content": prompt}]
28+
)
29+
30+
for chunk in response:
31+
if hasattr(chunk, "choices"):
32+
print(chunk.choices[0].delta.content or "", end="")
33+
else:
34+
print(chunk)
35+
36+
except Exception as e:
37+
print(f"An error occurred: {e}")
38+
39+
40+
Routellm("what is the square root of 12182382932.99")
41+
Routellm("Write me a short story")

src/langtrace_python_sdk/extensions/langtrace_filesystem.py

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,25 @@ def __new__(cls, value):
2727

2828

2929
class LangTraceFile(io.BytesIO):
30-
_host: str = os.environ.get("LANGTRACE_API_HOST", None) or LANGTRACE_REMOTE_URL
3130

3231
def __init__(self, fs: "LangTraceFileSystem", path: str, mode: OpenMode):
3332
super().__init__()
3433
self.fs = fs
3534
self.path = path
3635
self.mode = mode
36+
self._host: str = os.environ.get("LANGTRACE_API_HOST", LANGTRACE_REMOTE_URL)
37+
self._api_key: str = os.environ.get("LANGTRACE_API_KEY", None)
38+
if self._host.endswith("/api/trace"):
39+
self._host = self._host.replace("/api/trace", "")
40+
41+
if self._api_key is None:
42+
print(Fore.RED)
43+
print(
44+
f"Missing Langtrace API key, proceed to {self._host} to create one"
45+
)
46+
print("Set the API key as an environment variable LANGTRACE_API_KEY")
47+
print(Fore.RESET)
48+
return
3749

3850
def close(self) -> None:
3951
if not self.closed:
@@ -71,7 +83,7 @@ def upload_to_server(self, file_data: bytes) -> None:
7183
data=json.dumps(data),
7284
headers={
7385
"Content-Type": "application/json",
74-
"x-api-key": os.environ.get("LANGTRACE_API_KEY"),
86+
"x-api-key": self._api_key,
7587
},
7688
timeout=20,
7789
)
@@ -82,14 +94,26 @@ def upload_to_server(self, file_data: bytes) -> None:
8294

8395

8496
class LangTraceFileSystem(AbstractFileSystem):
85-
_host: str = os.environ.get("LANGTRACE_API_HOST", None) or LANGTRACE_REMOTE_URL
8697
protocol = "langtracefs"
8798
sep = "/"
8899

89100
def __init__(self, *args, **kwargs):
90101
super().__init__(*args, **kwargs)
91102
self.files = {}
92103
self.dirs = set()
104+
self._host: str = os.environ.get("LANGTRACE_API_HOST", LANGTRACE_REMOTE_URL)
105+
self._api_key: str = os.environ.get("LANGTRACE_API_KEY", None)
106+
if self._host.endswith("/api/trace"):
107+
self._host = self._host.replace("/api/trace", "")
108+
109+
if self._api_key is None:
110+
print(Fore.RED)
111+
print(
112+
f"Missing Langtrace API key, proceed to {self._host} to create one"
113+
)
114+
print("Set the API key as an environment variable LANGTRACE_API_KEY")
115+
print(Fore.RESET)
116+
return
93117

94118
def open(
95119
self,
@@ -118,7 +142,7 @@ def fetch_file_from_api(self, dataset_id: str) -> bytes:
118142
url=f"{self._host}/api/dataset/download?id={dataset_id}",
119143
headers={
120144
"Content-Type": "application/json",
121-
"x-api-key": os.environ.get("LANGTRACE_API_KEY"),
145+
"x-api-key": self._api_key,
122146
},
123147
timeout=20,
124148
)

src/langtrace_python_sdk/utils/with_root_span.py

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@
2525
from opentelemetry.trace import SpanKind
2626
from opentelemetry.trace.propagation import set_span_in_context
2727

28+
from langtrace_python_sdk.constants.exporter.langtrace_exporter import (
29+
LANGTRACE_REMOTE_URL,
30+
)
2831
from langtrace_python_sdk.constants.instrumentation.common import (
2932
LANGTRACE_ADDITIONAL_SPAN_ATTRIBUTES_KEY,
3033
)
@@ -142,7 +145,10 @@ class SendUserFeedback:
142145
_langtrace_api_key: str
143146

144147
def __init__(self):
145-
self._langtrace_host = os.environ["LANGTRACE_API_HOST"]
148+
self._langtrace_host = os.environ.get("LANGTRACE_API_HOST", LANGTRACE_REMOTE_URL)
149+
# When the host is set to /api/trace, remove the /api/trace
150+
if self._langtrace_host.endswith("/api/trace"):
151+
self._langtrace_host = self._langtrace_host.replace("/api/trace", "")
146152
self._langtrace_api_key = os.environ.get("LANGTRACE_API_KEY", None)
147153

148154
def evaluate(self, data: EvaluationAPIData) -> None:
@@ -155,6 +161,16 @@ def evaluate(self, data: EvaluationAPIData) -> None:
155161
print("Set the API key as an environment variable LANGTRACE_API_KEY")
156162
print(Fore.RESET)
157163
return
164+
165+
# convert spanId and traceId to hexadecimals
166+
span_hex_number = hex(int(data["spanId"], 10))[2:] # Convert to hex and remove the '0x' prefix
167+
formatted_span_hex_number = span_hex_number.zfill(16) # Pad with zeros to 16 characters
168+
data["spanId"] = f"0x{formatted_span_hex_number}"
169+
170+
trace_hex_number = hex(int(data["traceId"], 10))[2:] # Convert to hex and remove the '0x' prefix
171+
formatted_trace_hex_number = trace_hex_number.zfill(32) # Pad with zeros to 32 characters
172+
data["traceId"] = f"0x{formatted_trace_hex_number}"
173+
158174
evaluation = self.get_evaluation(data["spanId"])
159175
headers = {"x-api-key": self._langtrace_api_key}
160176
if evaluation is not None:
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "2.2.7"
1+
__version__ = "2.2.8"

0 commit comments

Comments
 (0)