|
| 1 | +"""LangSmith adapter for Eval Protocol. |
| 2 | +
|
| 3 | +This adapter pulls runs from LangSmith and converts them to EvaluationRow format, |
| 4 | +mirroring the behavior of the Langfuse adapter. |
| 5 | +
|
| 6 | +It supports extracting chat messages from inputs/outputs, and optionally includes |
| 7 | +tool calls and tool messages where present. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import logging |
| 13 | +from typing import Any, Dict, List, Optional |
| 14 | + |
| 15 | +from eval_protocol.models import EvaluationRow, InputMetadata, Message |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | +try: |
| 20 | + from langsmith import Client # type: ignore |
| 21 | + |
| 22 | + LANGSMITH_AVAILABLE = True |
| 23 | +except ImportError: |
| 24 | + LANGSMITH_AVAILABLE = False |
| 25 | + |
| 26 | + |
| 27 | +class LangSmithAdapter: |
| 28 | + """Adapter to pull data from LangSmith and convert to EvaluationRow format. |
| 29 | +
|
| 30 | + By default, fetches root runs from a project and maps inputs/outputs into |
| 31 | + `Message` objects. It supports a variety of input/output shapes commonly |
| 32 | + emitted by LangChain/LangGraph integrations, including: |
| 33 | + - inputs: { messages: [...] } | { prompt } | { user_input } | { input } | str | list[dict] |
| 34 | + - outputs: { messages: [...] } | { content } | { result } | { answer } | { output } | str | list[dict] |
| 35 | + """ |
| 36 | + |
| 37 | + def __init__(self, client: Optional[Client] = None) -> None: |
| 38 | + if not LANGSMITH_AVAILABLE: |
| 39 | + raise ImportError("LangSmith not installed. Install with: pip install langsmith") |
| 40 | + self.client = client or Client() |
| 41 | + |
| 42 | + def get_evaluation_rows( |
| 43 | + self, |
| 44 | + *, |
| 45 | + project_name: str, |
| 46 | + limit: int = 50, |
| 47 | + include_tool_calls: bool = True, |
| 48 | + ) -> List[EvaluationRow]: |
| 49 | + """Pull runs from LangSmith and convert to EvaluationRow format. |
| 50 | +
|
| 51 | + Args: |
| 52 | + project_name: LangSmith project to read runs from |
| 53 | + limit: Maximum number of rows to return |
| 54 | + include_tool_calls: Whether to include tool calling information when present |
| 55 | + """ |
| 56 | + rows: List[EvaluationRow] = [] |
| 57 | + |
| 58 | + # Prefer root runs; they usually contain messages in inputs/outputs when tracing app-level flows |
| 59 | + runs = list( |
| 60 | + self.client.list_runs( |
| 61 | + project_name=project_name, |
| 62 | + is_root=True, |
| 63 | + limit=limit, |
| 64 | + select=["id", "inputs", "outputs"], |
| 65 | + ) |
| 66 | + ) |
| 67 | + |
| 68 | + for r in runs: |
| 69 | + try: |
| 70 | + inp = getattr(r, "inputs", None) |
| 71 | + out = getattr(r, "outputs", None) |
| 72 | + |
| 73 | + ep_messages: List[Message] = [] |
| 74 | + # Prefer canonical conversation from outputs.messages if present to avoid duplicates |
| 75 | + if isinstance(out, dict) and isinstance(out.get("messages"), list): |
| 76 | + ep_messages.extend( |
| 77 | + self._extract_messages_from_payload( |
| 78 | + {"messages": out["messages"]}, include_tool_calls, is_output=True |
| 79 | + ) |
| 80 | + ) |
| 81 | + else: |
| 82 | + # Inputs → user messages |
| 83 | + ep_messages.extend(self._extract_messages_from_payload(inp, include_tool_calls)) |
| 84 | + # Outputs → assistant (and possible tool messages) |
| 85 | + ep_messages.extend(self._extract_messages_from_payload(out, include_tool_calls, is_output=True)) |
| 86 | + |
| 87 | + # Deduplicate consecutive identical user messages (common echo pattern) |
| 88 | + def _canon(text: Any) -> str: |
| 89 | + try: |
| 90 | + return " ".join(str(text or "").strip().lower().split()) |
| 91 | + except Exception: |
| 92 | + return str(text or "") |
| 93 | + |
| 94 | + deduped: List[Message] = [] |
| 95 | + for m in ep_messages: |
| 96 | + if deduped and m.role == "user" and deduped[-1].role == "user": |
| 97 | + if _canon(m.content) == _canon(deduped[-1].content): |
| 98 | + continue |
| 99 | + deduped.append(m) |
| 100 | + ep_messages = deduped |
| 101 | + |
| 102 | + if not ep_messages: |
| 103 | + continue |
| 104 | + |
| 105 | + rows.append( |
| 106 | + EvaluationRow( |
| 107 | + messages=ep_messages, |
| 108 | + input_metadata=InputMetadata( |
| 109 | + session_data={ |
| 110 | + "langsmith_run_id": str(getattr(r, "id", "")), |
| 111 | + "langsmith_project": project_name, |
| 112 | + } |
| 113 | + ), |
| 114 | + ) |
| 115 | + ) |
| 116 | + except Exception as e: |
| 117 | + logger.warning("Failed to convert run %s: %s", getattr(r, "id", ""), e) |
| 118 | + continue |
| 119 | + |
| 120 | + return rows |
| 121 | + |
| 122 | + def _extract_messages_from_payload( |
| 123 | + self, payload: Any, include_tool_calls: bool, *, is_output: bool = False |
| 124 | + ) -> List[Message]: |
| 125 | + messages: List[Message] = [] |
| 126 | + |
| 127 | + def _dict_to_message(msg_dict: Dict[str, Any]) -> Message: |
| 128 | + # Role |
| 129 | + role = msg_dict.get("role") |
| 130 | + if role is None: |
| 131 | + # Map LangChain types to roles if available |
| 132 | + msg_type = msg_dict.get("type") |
| 133 | + if msg_type == "human": |
| 134 | + role = "user" |
| 135 | + elif msg_type == "ai": |
| 136 | + role = "assistant" |
| 137 | + else: |
| 138 | + role = "assistant" if is_output else "user" |
| 139 | + |
| 140 | + content = msg_dict.get("content") |
| 141 | + # LangChain content parts |
| 142 | + if isinstance(content, list): |
| 143 | + text = " ".join([part.get("text", "") for part in content if isinstance(part, dict)]) |
| 144 | + content = text or str(content) |
| 145 | + |
| 146 | + name = msg_dict.get("name") |
| 147 | + |
| 148 | + tool_calls = None |
| 149 | + tool_call_id = None |
| 150 | + function_call = None |
| 151 | + if include_tool_calls: |
| 152 | + if "tool_calls" in msg_dict and isinstance(msg_dict["tool_calls"], list): |
| 153 | + try: |
| 154 | + from openai.types.chat.chat_completion_message_tool_call import ( |
| 155 | + ChatCompletionMessageToolCall, |
| 156 | + Function as ChatToolFunction, |
| 157 | + ) |
| 158 | + |
| 159 | + typed_calls: List[ChatCompletionMessageToolCall] = [] |
| 160 | + for tc in msg_dict["tool_calls"]: |
| 161 | + # Extract id/type/function fields from dicts or provider-native objects |
| 162 | + if isinstance(tc, dict): |
| 163 | + tc_id = tc.get("id", None) |
| 164 | + tc_type = tc.get("type", "function") or "function" |
| 165 | + fn = tc.get("function", {}) or {} |
| 166 | + fn_name = fn.get("name", None) |
| 167 | + fn_args = fn.get("arguments", None) |
| 168 | + else: |
| 169 | + tc_id = getattr(tc, "id", None) |
| 170 | + tc_type = getattr(tc, "type", None) or "function" |
| 171 | + f = getattr(tc, "function", None) |
| 172 | + fn_name = getattr(f, "name", None) if f is not None else None |
| 173 | + fn_args = getattr(f, "arguments", None) if f is not None else None |
| 174 | + |
| 175 | + # Build typed function object (arguments must be a string per OpenAI type) |
| 176 | + fn_obj = ChatToolFunction( |
| 177 | + name=str(fn_name) if fn_name is not None else "", |
| 178 | + arguments=str(fn_args) if fn_args is not None else "", |
| 179 | + ) |
| 180 | + typed_calls.append( |
| 181 | + ChatCompletionMessageToolCall( |
| 182 | + id=str(tc_id) if tc_id is not None else "", |
| 183 | + type="function", |
| 184 | + function=fn_obj, |
| 185 | + ) |
| 186 | + ) |
| 187 | + tool_calls = typed_calls |
| 188 | + except Exception: |
| 189 | + # If OpenAI types unavailable, leave None to satisfy type checker |
| 190 | + tool_calls = None |
| 191 | + if "tool_call_id" in msg_dict: |
| 192 | + tool_call_id = msg_dict.get("tool_call_id") |
| 193 | + if "function_call" in msg_dict: |
| 194 | + function_call = msg_dict.get("function_call") |
| 195 | + |
| 196 | + return Message( |
| 197 | + role=str(role), |
| 198 | + content=str(content) if content is not None else "", |
| 199 | + name=name, |
| 200 | + tool_call_id=tool_call_id, |
| 201 | + tool_calls=tool_calls, |
| 202 | + function_call=function_call, |
| 203 | + ) |
| 204 | + |
| 205 | + if isinstance(payload, dict): |
| 206 | + # Common patterns |
| 207 | + if isinstance(payload.get("messages"), list): |
| 208 | + for m in payload["messages"]: |
| 209 | + if isinstance(m, dict): |
| 210 | + messages.append(_dict_to_message(m)) |
| 211 | + else: |
| 212 | + messages.append(Message(role="assistant" if is_output else "user", content=str(m))) |
| 213 | + elif "prompt" in payload and isinstance(payload["prompt"], str): |
| 214 | + messages.append(Message(role="user" if not is_output else "assistant", content=str(payload["prompt"]))) |
| 215 | + elif "user_input" in payload and isinstance(payload["user_input"], str): |
| 216 | + messages.append( |
| 217 | + Message(role="user" if not is_output else "assistant", content=str(payload["user_input"])) |
| 218 | + ) |
| 219 | + elif "input" in payload and isinstance(payload["input"], str): |
| 220 | + messages.append(Message(role="user" if not is_output else "assistant", content=str(payload["input"]))) |
| 221 | + elif "content" in payload and isinstance(payload["content"], str): |
| 222 | + messages.append(Message(role="assistant", content=str(payload["content"]))) |
| 223 | + elif "result" in payload and isinstance(payload["result"], str): |
| 224 | + messages.append(Message(role="assistant", content=str(payload["result"]))) |
| 225 | + elif "answer" in payload and isinstance(payload["answer"], str): |
| 226 | + messages.append(Message(role="assistant", content=str(payload["answer"]))) |
| 227 | + elif "output" in payload and isinstance(payload["output"], str): |
| 228 | + messages.append(Message(role="assistant", content=str(payload["output"]))) |
| 229 | + else: |
| 230 | + # Fallback: stringify |
| 231 | + messages.append(Message(role="assistant" if is_output else "user", content=str(payload))) |
| 232 | + elif isinstance(payload, list): |
| 233 | + for m in payload: |
| 234 | + if isinstance(m, dict): |
| 235 | + messages.append(_dict_to_message(m)) |
| 236 | + else: |
| 237 | + messages.append(Message(role="assistant" if is_output else "user", content=str(m))) |
| 238 | + elif isinstance(payload, str): |
| 239 | + messages.append(Message(role="assistant" if is_output else "user", content=payload)) |
| 240 | + |
| 241 | + return messages |
| 242 | + |
| 243 | + |
| 244 | +def create_langsmith_adapter() -> LangSmithAdapter: |
| 245 | + return LangSmithAdapter() |
0 commit comments