-
Notifications
You must be signed in to change notification settings - Fork 3
feat: Update LangChain runners to implement Runner protocol returning RunnerResult #150
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jsonbailey
wants to merge
1
commit into
jb/aic-2388/openai-runner-protocol
Choose a base branch
from
jb/aic-2388/langchain-runner-protocol
base: jb/aic-2388/openai-runner-protocol
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
52 changes: 35 additions & 17 deletions
52
packages/ai-providers/server-ai-langchain/src/ldai_langchain/langchain_agent_runner.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,65 +1,83 @@ | ||
| from typing import Any | ||
| from typing import Any, Dict, List, Optional | ||
|
|
||
| from ldai import log | ||
| from ldai.providers import AgentResult, AgentRunner | ||
| from ldai.providers.types import LDAIMetrics | ||
| from ldai.providers.types import LDAIMetrics, RunnerResult | ||
|
|
||
| from ldai_langchain.langchain_helper import ( | ||
| extract_last_message_content, | ||
| get_tool_calls_from_response, | ||
| sum_token_usage_from_messages, | ||
| ) | ||
|
|
||
|
|
||
| class LangChainAgentRunner(AgentRunner): | ||
| class LangChainAgentRunner: | ||
| """ | ||
| CAUTION: | ||
| This feature is experimental and should NOT be considered ready for production use. | ||
| It may change or be removed without notice and is not subject to backwards | ||
| compatibility guarantees. | ||
|
|
||
| AgentRunner implementation for LangChain. | ||
| Runner implementation for a single LangChain agent. | ||
|
|
||
| Wraps a compiled LangChain agent graph (from ``langchain.agents.create_agent``) | ||
| and delegates execution to it. Tool calling and loop management are handled | ||
| internally by the graph. | ||
| Returned by LangChainRunnerFactory.create_agent(config, tools). | ||
| Returned by ``LangChainRunnerFactory.create_agent(config, tools)``. | ||
|
|
||
| Implements the unified :class:`~ldai.providers.runner.Runner` protocol. | ||
| """ | ||
|
|
||
| def __init__(self, agent: Any): | ||
| self._agent = agent | ||
|
|
||
| async def run(self, input: Any) -> AgentResult: | ||
| async def run( | ||
| self, | ||
| input: Any, | ||
| output_type: Optional[Dict[str, Any]] = None, | ||
| ) -> RunnerResult: | ||
| """ | ||
| Run the agent with the given input string. | ||
| Run the agent with the given input. | ||
|
|
||
| Delegates to the compiled LangChain agent, which handles | ||
| the tool-calling loop internally. | ||
|
|
||
| :param input: The user prompt or input to the agent | ||
| :return: AgentResult with output, raw response, and aggregated metrics | ||
| :param output_type: Reserved for future structured output support; | ||
| currently ignored. | ||
| :return: :class:`RunnerResult` with ``content``, ``raw`` response, and | ||
| metrics including aggregated token usage and observed ``tool_calls``. | ||
| """ | ||
| try: | ||
| result = await self._agent.ainvoke({ | ||
| "messages": [{"role": "user", "content": str(input)}] | ||
| }) | ||
| messages = result.get("messages", []) | ||
| output = extract_last_message_content(messages) | ||
| return AgentResult( | ||
| output=output, | ||
| raw=result, | ||
| messages: List[Any] = result.get("messages", []) | ||
| content = extract_last_message_content(messages) | ||
| tool_calls = self._extract_tool_calls(messages) | ||
| return RunnerResult( | ||
| content=content, | ||
| metrics=LDAIMetrics( | ||
| success=True, | ||
| usage=sum_token_usage_from_messages(messages), | ||
| tool_calls=tool_calls if tool_calls else None, | ||
| ), | ||
| raw=result, | ||
| ) | ||
| except Exception as error: | ||
| log.warning(f"LangChain agent run failed: {error}") | ||
| return AgentResult( | ||
| output="", | ||
| raw=None, | ||
| return RunnerResult( | ||
| content="", | ||
| metrics=LDAIMetrics(success=False, usage=None), | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def _extract_tool_calls(messages: List[Any]) -> List[str]: | ||
| """Collect tool call names from all messages in the agent output.""" | ||
| names: List[str] = [] | ||
| for msg in messages: | ||
| names.extend(get_tool_calls_from_response(msg)) | ||
| return names | ||
|
|
||
| def get_agent(self) -> Any: | ||
| """Return the underlying compiled LangChain agent.""" | ||
| return self._agent |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missing deprecated adapter methods breaks Judge evaluations
High Severity
The PR description states that legacy
invoke_model()andinvoke_structured_model()are "retained as deprecated adapters that delegate torun()for backward compatibility," but both methods were completely removed fromLangChainModelRunner. TheJudgeclass atpackages/sdk/server-ai/src/ldai/judge/__init__.py:79directly callsself._model_runner.invoke_structured_model(...), and the deprecatedManagedModel.invoke()atpackages/sdk/server-ai/src/ldai/managed_model.py:121callsself._model_runner.invoke_model(...). When aLangChainModelRunneris used as the judge's model runner (which happens viaRunnerFactory.create_model()), both paths will crash withAttributeErrorat runtime.Additional Locations (1)
packages/ai-providers/server-ai-langchain/src/ldai_langchain/langchain_model_runner.py#L36-L55Reviewed by Cursor Bugbot for commit 1aa1069. Configure here.