|
14 | 14 |
|
15 | 15 | import json |
16 | 16 | import logging |
| 17 | +import os |
17 | 18 | import uuid |
18 | 19 | from collections.abc import Awaitable, Callable, Sequence |
19 | 20 | from dataclasses import asdict, dataclass |
|
119 | 120 | LC_AgentMiddleware = Langchain_AgentMiddleware[Any, "InvokeContext", Any] |
120 | 121 | LC_ModelRequest = Langchain_ModelRequest["InvokeContext"] |
121 | 122 |
|
| 123 | +# Set to True to enable debugging mode. |
| 124 | +_DEBUG = False |
| 125 | + |
| 126 | +# Disallow _DEBUG == True in CI. |
| 127 | +# Github actions sets the CI env var. |
| 128 | +if _DEBUG and os.environ.get("CI") is not None: |
| 129 | + raise Exception( |
| 130 | + "_DEBUG can only be used in a local dev env and shouldn't ever be committed!" |
| 131 | + ) |
| 132 | + |
122 | 133 | # Represents a prefix reserved only for internal use. |
123 | 134 | # No user-visible tool or subagent name can be prefixed with it. |
124 | 135 | RESERVED_LC_TOOL_PREFIX = "__" |
@@ -475,6 +486,48 @@ def unpack_tool_call(self, call: LC_ToolCall) -> LC_ToolCall: |
475 | 486 | lc_middleware.append(_ThreadIDMiddleware()) |
476 | 487 | lc_middleware.append(_SubagentArgumentPacker()) |
477 | 488 |
|
| 489 | + class _DEBUGMiddleware(LC_AgentMiddleware): |
| 490 | + @override |
| 491 | + async def awrap_model_call( |
| 492 | + self, |
| 493 | + request: LC_ModelRequest, |
| 494 | + handler: Callable[[LC_ModelRequest], Awaitable[LC_ModelCallResult]], |
| 495 | + ) -> LC_ModelCallResult: |
| 496 | + from rich import print |
| 497 | + |
| 498 | + print("LLM CALL", request) |
| 499 | + try: |
| 500 | + resp = await handler(request) |
| 501 | + except Exception as e: |
| 502 | + print("LLM FAILURE", e) |
| 503 | + raise |
| 504 | + |
| 505 | + print("LLM RESPONSE", resp) |
| 506 | + return resp |
| 507 | + |
| 508 | + @override |
| 509 | + async def awrap_tool_call( |
| 510 | + self, |
| 511 | + request: LC_ToolCallRequest, |
| 512 | + handler: Callable[ |
| 513 | + [LC_ToolCallRequest], Awaitable[LC_ToolMessage | LC_Command[None]] |
| 514 | + ], |
| 515 | + ) -> LC_ToolMessage | LC_Command[None]: |
| 516 | + from rich import print |
| 517 | + |
| 518 | + print("TOOL CALL", request) |
| 519 | + try: |
| 520 | + resp = await handler(request) |
| 521 | + except Exception as e: |
| 522 | + print("TOOL FAILURE", e) |
| 523 | + raise |
| 524 | + |
| 525 | + print("TOOL RESPONSE", resp) |
| 526 | + return resp |
| 527 | + |
| 528 | + if _DEBUG: |
| 529 | + lc_middleware.append(_DEBUGMiddleware()) |
| 530 | + |
478 | 531 | response_format = None |
479 | 532 | if agent.output_schema is not None: |
480 | 533 | if _supports_provider_strategy(model_impl): |
|
0 commit comments