karenina.adapters.langchain_deep_agents¶
langchain_deep_agents
¶
LangChain Deep Agents adapter for natively agentic evaluation.
This adapter provides AgentPort, LLMPort, and ParserPort implementations using LangChain Deep Agents (create_deep_agent). It enables provider-agnostic agentic evaluation with built-in planning, context management, and subagent orchestration.
Requires: pip install deepagents langchain-mcp-adapters
Adapter classes
- DeepAgentsAgentAdapter: Agent loops via create_deep_agent with MCP support
- DeepAgentsLLMAdapter: Simple LLM invocation via single-turn agent
- DeepAgentsParserAdapter: Structured output parsing
Utilities
- DeepAgentsMessageConverter: Convert between unified Message and LangGraph types
- check_deep_agents_available: Check if deepagents is installed
- convert_mcp_to_tools: Convert MCPServerConfig to LangChain tools
- extract_deep_agents_usage: Extract UsageMetadata from agent results
- deep_agents_messages_to_raw_trace: Format messages as raw trace string
Classes¶
DeepAgentsAgentAdapter
¶
Agent adapter using LangChain Deep Agents' create_deep_agent.
This adapter implements the AgentPort Protocol for agent execution with built-in planning tools, filesystem operations, subagent delegation, and context management. Uses create_deep_agent() which returns a compiled LangGraph graph.
The adapter handles: - Message conversion from unified Message to prompt string - Model initialization via init_chat_model - Agent creation and invocation via LangGraph - Dual trace output (raw_trace string and trace_messages list) - Usage metadata extraction from AIMessage response_metadata - Recursion limit detection from LangGraph state
Example
config = ModelConfig( ... id="test", ... model_name="claude-sonnet-4-20250514", ... model_provider="anthropic", ... interface="langchain_deep_agents", ... ) adapter = DeepAgentsAgentAdapter(config) result = await adapter.arun( ... messages=[Message.user("What files are in /tmp?")], ... config=AgentConfig(max_turns=10), ... ) print(result.final_response)
Source code in src/karenina/adapters/langchain_deep_agents/agent.py
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 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | |
Functions¶
__init__
¶
__init__(model_config: ModelConfig) -> None
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_config
¶ |
ModelConfig
|
Configuration specifying model, provider, and interface. |
required |
Source code in src/karenina/adapters/langchain_deep_agents/agent.py
aclose
async
¶
Close underlying resources.
Deep Agents manages its own cleanup via LangGraph's compiled graph, so this is a no-op. Provided for interface consistency with other adapters that do require cleanup.
Source code in src/karenina/adapters/langchain_deep_agents/agent.py
arun
async
¶
arun(
messages: list[Message],
tools: list[Tool] | None = None,
mcp_servers: dict[str, MCPServerConfig] | None = None,
config: AgentConfig | None = None,
) -> AgentResult
Execute an agent loop with optional tools and MCP servers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
¶ |
list[Message]
|
Initial conversation messages. |
required |
tools
¶ |
list[Tool] | None
|
Optional list of Tool definitions the agent can invoke. |
None
|
mcp_servers
¶ |
dict[str, MCPServerConfig] | None
|
Optional dict of MCP server configurations. |
None
|
config
¶ |
AgentConfig | None
|
Optional AgentConfig for execution parameters. |
None
|
Returns:
| Type | Description |
|---|---|
AgentResult
|
AgentResult with final response, traces, usage, and metadata. |
Raises:
| Type | Description |
|---|---|
AgentExecutionError
|
If the agent fails during execution. |
AgentTimeoutError
|
If execution exceeds the timeout. |
AgentResponseError
|
If the response is malformed or invalid. |
Source code in src/karenina/adapters/langchain_deep_agents/agent.py
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 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | |
run
¶
run(
messages: list[Message],
tools: list[Tool] | None = None,
mcp_servers: dict[str, MCPServerConfig] | None = None,
config: AgentConfig | None = None,
) -> AgentResult
Synchronous wrapper for arun().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
¶ |
list[Message]
|
Initial conversation messages. |
required |
tools
¶ |
list[Tool] | None
|
Optional list of Tool definitions. |
None
|
mcp_servers
¶ |
dict[str, MCPServerConfig] | None
|
Optional MCP server configurations. |
None
|
config
¶ |
AgentConfig | None
|
Optional AgentConfig for execution parameters. |
None
|
Returns:
| Type | Description |
|---|---|
AgentResult
|
AgentResult from the agent execution. |
Raises:
| Type | Description |
|---|---|
AgentExecutionError
|
If the agent fails during execution. |
AgentTimeoutError
|
If execution exceeds the timeout. |
AgentResponseError
|
If the response is malformed or invalid. |
Source code in src/karenina/adapters/langchain_deep_agents/agent.py
DeepAgentsLLMAdapter
¶
LLM adapter using LangChain's init_chat_model for single-turn calls.
This adapter implements the LLMPort Protocol for simple LLM invocation without agent loops. Uses the LangChain model directly for efficiency.
Example
config = ModelConfig( ... id="test", ... model_name="claude-sonnet-4-20250514", ... model_provider="anthropic", ... interface="langchain_deep_agents", ... ) adapter = DeepAgentsLLMAdapter(config) response = await adapter.ainvoke([Message.user("Hello!")]) print(response.content)
Source code in src/karenina/adapters/langchain_deep_agents/llm.py
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 | |
Attributes¶
capabilities
property
¶
capabilities: PortCapabilities
Declare adapter capabilities.
Returns:
| Type | Description |
|---|---|
PortCapabilities
|
PortCapabilities with system_prompt=True and structured_output=True. |
Functions¶
__init__
¶
__init__(
model_config: ModelConfig,
*,
_structured_schema: type[BaseModel] | None = None,
) -> None
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_config
¶ |
ModelConfig
|
Configuration specifying model, provider, and interface. |
required |
_structured_schema
¶ |
type[BaseModel] | None
|
Internal; schema for structured output mode. |
None
|
Source code in src/karenina/adapters/langchain_deep_agents/llm.py
ainvoke
async
¶
ainvoke(messages: list[Message]) -> LLMResponse
Invoke the LLM asynchronously.
Converts karenina Messages to LangChain format, invokes the model, and converts the response back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
¶ |
list[Message]
|
List of messages forming the conversation. |
required |
Returns:
| Type | Description |
|---|---|
LLMResponse
|
LLMResponse containing the generated content and usage metadata. |
Source code in src/karenina/adapters/langchain_deep_agents/llm.py
invoke
¶
invoke(messages: list[Message]) -> LLMResponse
Invoke the LLM synchronously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
¶ |
list[Message]
|
List of messages forming the conversation. |
required |
Returns:
| Type | Description |
|---|---|
LLMResponse
|
LLMResponse containing the generated content and usage metadata. |
Source code in src/karenina/adapters/langchain_deep_agents/llm.py
with_structured_output
¶
with_structured_output(
schema: type[BaseModel],
*,
max_retries: int | None = None,
) -> DeepAgentsLLMAdapter
Return a new adapter configured for structured output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schema
¶ |
type[BaseModel]
|
A Pydantic model class defining the output structure. |
required |
max_retries
¶ |
int | None
|
Ignored (LangChain handles retries internally). |
None
|
Returns:
| Type | Description |
|---|---|
DeepAgentsLLMAdapter
|
A new DeepAgentsLLMAdapter configured with the schema. |
Source code in src/karenina/adapters/langchain_deep_agents/llm.py
DeepAgentsMessageConverter
¶
Convert between karenina's unified Message and LangGraph message types.
Deep Agents accepts messages as dicts with role/content keys for invocation, and returns LangGraph BaseMessage subclasses in results.
Source code in src/karenina/adapters/langchain_deep_agents/messages.py
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 | |
Functions¶
extract_system_prompt
¶
Extract system prompt from messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
¶ |
list[Message]
|
List of karenina Message objects. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
Combined system prompt text, or None if no system messages. |
Source code in src/karenina/adapters/langchain_deep_agents/messages.py
from_provider
¶
from_provider(lc_messages: list[Any]) -> list[Message]
Convert LangGraph BaseMessage list to karenina Messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lc_messages
¶ |
list[Any]
|
List of LangGraph message objects. |
required |
Returns:
| Type | Description |
|---|---|
list[Message]
|
List of karenina Message objects. |
Source code in src/karenina/adapters/langchain_deep_agents/messages.py
to_langchain_messages
¶
Convert karenina messages to LangGraph-compatible dicts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
¶ |
list[Message]
|
List of karenina Message objects. |
required |
Returns:
| Type | Description |
|---|---|
list[dict[str, str]]
|
List of message dicts with role and content keys. |
Source code in src/karenina/adapters/langchain_deep_agents/messages.py
to_prompt_string
¶
Convert user/assistant messages to a prompt string.
System messages are excluded (use extract_system_prompt instead).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
¶ |
list[Message]
|
List of karenina Message objects. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Concatenated prompt string from non-system messages. |
Source code in src/karenina/adapters/langchain_deep_agents/messages.py
DeepAgentsParserAdapter
¶
Parser adapter using LangChain's structured output for data extraction.
Implements the ParserPort Protocol by using with_structured_output() on the LangChain model. Falls back to JSON extraction from text if structured output is not available.
Example
from pydantic import BaseModel, Field class Answer(BaseModel): ... gene: str = Field(description="Gene name") parser = DeepAgentsParserAdapter(config) result = await parser.aparse_to_pydantic(messages, Answer) print(result.parsed.gene)
Source code in src/karenina/adapters/langchain_deep_agents/parser.py
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 | |
Attributes¶
capabilities
property
¶
capabilities: PortCapabilities
Declare adapter capabilities.
Returns:
| Type | Description |
|---|---|
PortCapabilities
|
PortCapabilities with system_prompt=True and structured_output=True. |
Functions¶
__init__
¶
__init__(model_config: ModelConfig) -> None
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_config
¶ |
ModelConfig
|
Configuration specifying model, provider, and interface. |
required |
Source code in src/karenina/adapters/langchain_deep_agents/parser.py
aparse_to_pydantic
async
¶
aparse_to_pydantic(
messages: list[Any], schema: type[T]
) -> ParsePortResult[T]
Parse pre-assembled prompt messages into a Pydantic model.
Uses LangChain's with_structured_output() to constrain the LLM. Falls back to JSON extraction if structured output fails.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
¶ |
list[Any]
|
Pre-assembled prompt messages (system + user). |
required |
schema
¶ |
type[T]
|
A Pydantic model class defining the expected structure. |
required |
Returns:
| Type | Description |
|---|---|
ParsePortResult[T]
|
ParsePortResult containing the parsed model and usage metadata. |
Raises:
| Type | Description |
|---|---|
ParseError
|
If the LLM fails to produce valid structured data. |
Source code in src/karenina/adapters/langchain_deep_agents/parser.py
parse_to_pydantic
¶
parse_to_pydantic(
messages: list[Any], schema: type[T]
) -> ParsePortResult[T]
Parse pre-assembled prompt messages (sync wrapper).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
¶ |
list[Any]
|
Pre-assembled prompt messages. |
required |
schema
¶ |
type[T]
|
A Pydantic model class defining the expected structure. |
required |
Returns:
| Type | Description |
|---|---|
ParsePortResult[T]
|
ParsePortResult containing the parsed model and usage metadata. |
Source code in src/karenina/adapters/langchain_deep_agents/parser.py
Functions¶
check_deep_agents_available
¶
check_deep_agents_available() -> AdapterAvailability
Check if the deepagents package is installed.
Returns:
| Type | Description |
|---|---|
AdapterAvailability
|
AdapterAvailability with status and installation instructions. |
Source code in src/karenina/adapters/langchain_deep_agents/availability.py
convert_mcp_to_tools
async
¶
convert_mcp_to_tools(
mcp_servers: dict[str, Any] | None,
) -> list[Any]
Convert MCP server configs to LangChain tools via langchain-mcp-adapters.
Creates a MultiServerMCPClient, connects to all servers, and returns their tools as LangChain BaseTool instances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
dict[str, Any] | None
|
Dict mapping server names to MCPServerConfig. |
required |
Returns:
| Type | Description |
|---|---|
list[Any]
|
List of LangChain BaseTool instances from all MCP servers. |
Source code in src/karenina/adapters/langchain_deep_agents/mcp.py
deep_agents_messages_to_raw_trace
¶
deep_agents_messages_to_raw_trace(
messages: list[Any], include_user_messages: bool = False
) -> str
Convert LangGraph messages to raw trace string format.
Produces delimited trace compatible with existing karenina infrastructure (regex highlighting, database storage, backward compatibility).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
list[Any]
|
List of LangGraph BaseMessage objects. |
required |
|
bool
|
If True, include HumanMessage in trace. |
False
|
Returns:
| Type | Description |
|---|---|
str
|
Formatted trace string with --- delimiters. |
Source code in src/karenina/adapters/langchain_deep_agents/trace.py
extract_deep_agents_usage
¶
extract_deep_agents_usage(
messages: list[Any], model: str | None = None
) -> UsageMetadata
Extract aggregated usage metadata from LangGraph messages.
Sums token counts across all AIMessage instances in the conversation. Token counts come from AIMessage.usage_metadata (preferred) or AIMessage.response_metadata.token_usage (fallback).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
list[Any]
|
List of LangGraph BaseMessage objects. |
required |
|
str | None
|
Model name to include in usage metadata. |
None
|
Returns:
| Type | Description |
|---|---|
UsageMetadata
|
Aggregated UsageMetadata for the entire agent run. |
Source code in src/karenina/adapters/langchain_deep_agents/usage.py
wrap_deep_agents_error
¶
wrap_deep_agents_error(
error: Exception,
) -> tuple[Exception, bool]
Map a Deep Agents / LangGraph exception to a karenina exception.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Exception
|
The original exception from Deep Agents or LangGraph. |
required |
Returns:
| Type | Description |
|---|---|
Exception
|
Tuple of (mapped_exception, limit_reached). The limit_reached flag |
bool
|
is True when the error indicates the agent hit a recursion or turn limit. |