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
- deep_agents_messages_to_trace_messages: Structured trace_messages with per-call usage
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
Global concurrency cap: max_concurrent_requests (GlobalLLMLimiter)
gates single-turn LLM adapter calls and langchain-based agent model
calls only. This agent's internal model calls run outside that cap.
They were never semaphore-gated, so this is the honest current state
rather than a regression.
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
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 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 | |
Attributes¶
capabilities
property
¶
capabilities: PortCapabilities
Declare adapter capabilities.
Returns:
| Type | Description |
|---|---|
PortCapabilities
|
PortCapabilities implied by the configured DeepAgents backend. |
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,
_partial_result_store: _PartialResultStore
| 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
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 | |
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
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 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 | |
Attributes¶
capabilities
property
¶
capabilities: PortCapabilities
Declare adapter capabilities.
Returns:
| Type | Description |
|---|---|
PortCapabilities
|
PortCapabilities with system_prompt, structured_output, and streaming support. |
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
aclose
async
¶
Close underlying resources.
No resources to clean up: the LangChain model is created fresh per ainvoke() call. Provided for interface consistency with other adapters.
ainvoke
async
¶
ainvoke(messages: list[Message]) -> LLMResponse
Invoke the LLM asynchronously with automatic retry for transient errors.
Converts karenina Messages to LangChain format, invokes the model through RetryExecutor (per-category retry budgets for connection, timeout, rate limit, and server errors), 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
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 | |
astream
¶
astream(
messages: list[Message],
) -> AbstractAsyncContextManager[StreamingLLMResponse]
Stream LLM response using LangChain's cross-provider astream.
Stream ESTABLISHMENT (opening the LangChain astream and fetching the first chunk) routes through RetryExecutor, so transient connection-setup failures (including langchain-openai's cross event loop pooled-connection errors) retry with per-category budgets. Each retry recreates the stream from scratch. Once established, the stream is never retried mid-flight.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
¶ |
list[Message]
|
List of unified Message objects. |
required |
Returns:
| Type | Description |
|---|---|
AbstractAsyncContextManager[StreamingLLMResponse]
|
Async context manager yielding a StreamingLLMResponse that |
AbstractAsyncContextManager[StreamingLLMResponse]
|
can be iterated for text chunks. |
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
stream_invoke
¶
stream_invoke(
messages: list[Message], timeout: float | None = None
) -> LLMResponse
Stream with wall-clock timeout synchronously.
Uses streaming internally so that partial content can be captured on timeout. Returns the same LLMResponse type as invoke(). Retries via RetryExecutor on transient errors (including StreamingTimeoutError with zero content, classified as RATE_LIMIT for queue congestion). The inner stream-establishment retry used by the bare astream path is disabled on this path, so this outer executor is the single retry layer and connection attempts are not amplified multiplicatively.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
messages
¶ |
list[Message]
|
List of unified Message objects. |
required |
timeout
¶ |
float | None
|
Wall-clock timeout in seconds. None means no timeout. |
None
|
Returns:
| Type | Description |
|---|---|
LLMResponse
|
LLMResponse with accumulated content. |
Raises:
| Type | Description |
|---|---|
StreamingTimeoutError
|
If retries are exhausted and the stream still exceeds the wall-clock timeout. |
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
|
Not supported by this adapter. A warning is emitted if a non-None value is provided. See karenina.ports.llm.LLMPort.with_structured_output for the cross-adapter contract (LangChain and Claude Tool respect max_retries, this adapter and claude_agent_sdk warn and ignore). |
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
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 | |
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
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 | |
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
aclose
async
¶
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
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 | |
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,
exit_stack: AsyncExitStack,
) -> list[Any]
Convert MCP server configs to LangChain tools via langchain-mcp-adapters.
Creates a MultiServerMCPClient registered with the provided exit_stack so that MCP sessions remain open for the lifetime of the caller's exit_stack context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
dict[str, Any] | None
|
Dict mapping server names to MCPServerConfig. |
required |
|
AsyncExitStack
|
AsyncExitStack managing session lifecycles. Sessions remain open until the exit stack closes. |
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 the canonical karenina trace format shared by the langchain,
claude_agent_sdk, and manual adapters: one --- AI Message ---
section per turn carrying the text followed by an inline Tool Calls:
block, and --- Tool Message (call_id: <id>) --- for each tool
result. Thinking content surfaces as a separate --- Thinking ---
section before the AI Message for that turn.
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 |
str
|
regex highlighting, database storage, and the trace-evaluation |
str
|
infrastructure shared with the other adapters. |
Source code in src/karenina/adapters/langchain_deep_agents/trace.py
deep_agents_messages_to_trace_messages
¶
deep_agents_messages_to_trace_messages(
messages: list[Any], include_user_messages: bool = False
) -> list[dict[str, Any]]
Convert LangGraph messages to structured TraceMessage list.
Produces the structured list[dict] format consumed by the frontend TraceMessage component. Each assistant entry preserves per-call usage_metadata when the underlying AIMessage reports it (so post-hoc audits of token usage / cache hits per turn remain possible).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
list[Any]
|
List of LangGraph BaseMessage objects. |
required |
|
bool
|
If True, include HumanMessage entries. Defaults to False to match the existing raw_trace behavior. |
False
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
List of TraceMessage dicts with role, content, block_index, and |
list[dict[str, Any]]
|
optional tool_calls, tool_result, and usage_metadata fields. |
Source code in src/karenina/adapters/langchain_deep_agents/trace.py
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 | |
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. |