Repository navigation
Expand file tree
/
Copy pathlangsmith_bridge.py
More file actions
265 lines (233 loc) · 8.46 KB
/
Copy pathlangsmith_bridge.py
File metadata and controls
265 lines (233 loc) · 8.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
"""Optional LangSmith REST helpers: validate credentials + wrap in-app LLM calls."""
from __future__ import annotations
import json
import os
import uuid
from datetime import datetime, timedelta, timezone
from typing import Any, Callable
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, urlopen
API_BASE = "https://api.smith.langchain.com"
def _utc_now() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
def _headers(api_key: str) -> dict[str, str]:
return {
"Content-Type": "application/json",
"x-api-key": api_key,
}
def resolve_creds(cfg: dict[str, Any] | None = None) -> tuple[str, str]:
cfg = cfg or {}
key = (cfg.get("api_key") or os.environ.get("LANGSMITH_API_KEY") or "").strip()
project = (cfg.get("project") or os.environ.get("LANGSMITH_PROJECT") or "").strip()
return key, project
def _http_json(method: str, url: str, api_key: str, body: dict[str, Any] | None = None) -> Any:
data = None if body is None else json.dumps(body).encode("utf-8")
req = Request(url, data=data, headers=_headers(api_key), method=method)
with urlopen(req, timeout=45) as resp:
raw = resp.read().decode("utf-8")
if not raw:
return None
return json.loads(raw)
def resolve_session(api_key: str, project_name: str) -> dict[str, Any] | None:
"""Resolve a LangSmith project/session by exact name (case-insensitive fallback)."""
name = (project_name or "").strip()
if not name:
return None
try:
rows = _http_json("GET", f"{API_BASE}/sessions?name={quote(name)}&limit=20", api_key)
except (HTTPError, URLError, TimeoutError, json.JSONDecodeError):
rows = []
if isinstance(rows, list):
for s in rows:
if isinstance(s, dict) and (s.get("name") or "") == name:
return s
for s in rows:
if isinstance(s, dict) and (s.get("name") or "").lower() == name.lower():
return s
# Fallback: scan recent sessions
try:
rows = _http_json("GET", f"{API_BASE}/sessions?limit=50", api_key)
except (HTTPError, URLError, TimeoutError, json.JSONDecodeError):
return None
if not isinstance(rows, list):
return None
for s in rows:
if isinstance(s, dict) and (s.get("name") or "").lower() == name.lower():
return s
return None
def query_runs(
*,
api_key: str,
project_name: str,
limit: int = 20,
select: list[str] | None = None,
) -> dict[str, Any]:
"""List recent runs for a project. Resolves session id first (required by current API)."""
session = resolve_session(api_key, project_name)
if not session or not session.get("id"):
return {
"ok": False,
"error": f"LangSmith project/session not found: {project_name!r}",
"runs": [],
}
start = (datetime.now(timezone.utc) - timedelta(days=30)).replace(microsecond=0)
body = {
"session": [session["id"]],
"limit": min(max(limit, 1), 50),
"start_time": start.isoformat().replace("+00:00", "Z"),
"select": select
or ["id", "name", "inputs", "outputs", "start_time", "end_time", "error", "extra"],
}
try:
payload = _http_json("POST", f"{API_BASE}/runs/query", api_key, body)
except HTTPError as exc:
detail = exc.read().decode("utf-8", errors="replace")[:400]
return {"ok": False, "error": f"HTTP {exc.code}: {detail or exc.reason}", "runs": []}
except (URLError, TimeoutError, json.JSONDecodeError) as exc:
return {"ok": False, "error": str(exc), "runs": []}
runs = payload.get("runs") if isinstance(payload, dict) else None
if not isinstance(runs, list):
runs = payload if isinstance(payload, list) else []
return {
"ok": True,
"project": session.get("name") or project_name,
"session_id": session["id"],
"runs": runs,
}
def validate_langsmith(*, api_key: str | None = None, project: str | None = None) -> dict[str, Any]:
"""Credential check: key works + project resolves; sample up to 1 run."""
key = (api_key or os.environ.get("LANGSMITH_API_KEY") or "").strip()
project_name = (project or os.environ.get("LANGSMITH_PROJECT") or "").strip()
if not key:
return {"ok": False, "error": "LANGSMITH_API_KEY not set"}
if not project_name:
return {"ok": False, "error": "LANGSMITH_PROJECT not set"}
try:
_http_json("GET", f"{API_BASE}/info", key)
except HTTPError as exc:
detail = exc.read().decode("utf-8", errors="replace")[:200]
return {"ok": False, "error": f"HTTP {exc.code}: {detail or exc.reason}"}
except (URLError, TimeoutError, json.JSONDecodeError) as exc:
return {"ok": False, "error": str(exc)}
q = query_runs(api_key=key, project_name=project_name, limit=1, select=["id", "name", "start_time"])
if not q.get("ok"):
return q
runs = q.get("runs") or []
sample = runs[0] if runs and isinstance(runs[0], dict) else None
return {
"ok": True,
"project": q.get("project") or project_name,
"session_id": q.get("session_id"),
"runs_sampled": len(runs),
"sample_name": sample.get("name") if sample else None,
}
def _create_run(
*,
api_key: str,
session_id: str,
session_name: str,
name: str,
inputs: dict[str, Any],
run_id: str,
extra: dict[str, Any] | None = None,
) -> None:
body = {
"id": run_id,
"name": name,
"run_type": "llm",
"inputs": inputs,
"start_time": _utc_now(),
"session_id": session_id,
"session_name": session_name,
"extra": extra or {},
}
_http_json("POST", f"{API_BASE}/runs", api_key, body)
def _end_run(
*,
api_key: str,
run_id: str,
outputs: dict[str, Any],
error: str | None = None,
) -> None:
body: dict[str, Any] = {
"outputs": outputs,
"end_time": _utc_now(),
}
if error:
body["error"] = error
_http_json("PATCH", f"{API_BASE}/runs/{run_id}", api_key, body)
def wrap_llm_call(
*,
cfg: dict[str, Any] | None,
model: str,
messages: list[Any],
call: Callable[[], dict[str, Any]],
) -> dict[str, Any]:
"""
If langsmith.tracing is enabled and credentials exist, create/end a LangSmith run
around `call()` and attach `trace` onto the result. Failures in tracing are soft —
the LLM result is still returned (with `trace_error` if needed).
"""
cfg = cfg or {}
if not cfg.get("tracing"):
return call()
key, project = resolve_creds(cfg)
if not key or not project:
result = call()
result["trace_error"] = "LangSmith tracing on but api_key/project missing"
return result
session = resolve_session(key, project)
if not session or not session.get("id"):
result = call()
result["trace_error"] = f"LangSmith project/session not found: {project!r}"
return result
run_id = str(uuid.uuid4())
name = f"codebase-graph/{model or 'chat'}"
session_id = str(session["id"])
session_name = str(session.get("name") or project)
try:
_create_run(
api_key=key,
session_id=session_id,
session_name=session_name,
name=name,
inputs={"messages": messages},
run_id=run_id,
extra={"metadata": {"app": "codebase-graph", "model": model}},
)
except Exception as exc: # noqa: BLE001
result = call()
result["trace_error"] = f"LangSmith create failed: {exc}"
return result
err_msg: str | None = None
try:
result = call()
except Exception as exc:
err_msg = str(exc)
try:
_end_run(api_key=key, run_id=run_id, outputs={}, error=err_msg)
except Exception: # noqa: BLE001
pass
raise
try:
_end_run(
api_key=key,
run_id=run_id,
outputs={"content": result.get("content") or ""},
)
except Exception as exc: # noqa: BLE001
result["trace_error"] = f"LangSmith end failed: {exc}"
result["trace"] = {
"runs": [
{
"id": run_id,
"name": name,
"project": session_name,
"session_id": session_id,
"start_time": _utc_now(),
}
],
"tool_calls": [],
}
return result