libs/langchain/langchain_classic/agents/initialize.py PYTHON 117 lines View on github.com → Search inside
1"""Load agent."""23import contextlib4from collections.abc import Sequence5from typing import Any67from langchain_core._api import deprecated8from langchain_core.callbacks import BaseCallbackManager9from langchain_core.language_models import BaseLanguageModel10from langchain_core.tools import BaseTool1112from langchain_classic._api.deprecation import AGENT_DEPRECATION_WARNING13from langchain_classic.agents.agent import AgentExecutor14from langchain_classic.agents.agent_types import AgentType15from langchain_classic.agents.loading import load_agent16from langchain_classic.agents.types import AGENT_TO_CLASS171819@deprecated(20    "0.1.0",21    message=AGENT_DEPRECATION_WARNING,22    removal="2.0.0",23)24def initialize_agent(25    tools: Sequence[BaseTool],26    llm: BaseLanguageModel,27    agent: AgentType | None = None,28    callback_manager: BaseCallbackManager | None = None,29    agent_path: str | None = None,30    agent_kwargs: dict | None = None,31    *,32    tags: Sequence[str] | None = None,33    **kwargs: Any,34) -> AgentExecutor:35    """Load an agent executor given tools and LLM.3637    !!! warning3839        This function is no deprecated in favor of40        [`create_agent`][langchain.agents.create_agent] from the `langchain`41        package, which provides a more flexible agent factory with middleware42        support, structured output, and integration with LangGraph.4344        For migration guidance, see45        [Migrating to langchain v1](https://docs.langchain.com/oss/python/migrate/langchain-v1)46        and47        [Migrating from AgentExecutor](https://python.langchain.com/docs/how_to/migrate_agent/).4849    Args:50        tools: List of tools this agent has access to.51        llm: Language model to use as the agent.52        agent: Agent type to use. If `None` and agent_path is also None, will default53            to AgentType.ZERO_SHOT_REACT_DESCRIPTION.54        callback_manager: CallbackManager to use. Global callback manager is used if55            not provided.56        agent_path: Path to serialized agent to use. If `None` and agent is also None,57            will default to AgentType.ZERO_SHOT_REACT_DESCRIPTION.58        agent_kwargs: Additional keyword arguments to pass to the underlying agent.59        tags: Tags to apply to the traced runs.60        kwargs: Additional keyword arguments passed to the agent executor.6162    Returns:63        An agent executor.6465    Raises:66        ValueError: If both `agent` and `agent_path` are specified.67        ValueError: If `agent` is not a valid agent type.68        ValueError: If both `agent` and `agent_path` are None.69    """70    tags_ = list(tags) if tags else []71    if agent is None and agent_path is None:72        agent = AgentType.ZERO_SHOT_REACT_DESCRIPTION73    if agent is not None and agent_path is not None:74        msg = (75            "Both `agent` and `agent_path` are specified, "76            "but at most only one should be."77        )78        raise ValueError(msg)79    if agent is not None:80        if agent not in AGENT_TO_CLASS:81            msg = (82                f"Got unknown agent type: {agent}. "83                f"Valid types are: {AGENT_TO_CLASS.keys()}."84            )85            raise ValueError(msg)86        tags_.append(agent.value if isinstance(agent, AgentType) else agent)87        agent_cls = AGENT_TO_CLASS[agent]88        agent_kwargs = agent_kwargs or {}89        agent_obj = agent_cls.from_llm_and_tools(90            llm,91            tools,92            callback_manager=callback_manager,93            **agent_kwargs,94        )95    elif agent_path is not None:96        agent_obj = load_agent(97            agent_path,98            llm=llm,99            tools=tools,100            callback_manager=callback_manager,101        )102        with contextlib.suppress(NotImplementedError):103            # TODO: Add tags from the serialized object directly.104            tags_.append(agent_obj._agent_type)  # noqa: SLF001105    else:106        msg = (107            "Somehow both `agent` and `agent_path` are None, this should never happen."108        )109        raise ValueError(msg)110    return AgentExecutor.from_agent_and_tools(111        agent=agent_obj,112        tools=tools,113        callback_manager=callback_manager,114        tags=tags_,115        **kwargs,116    )

Code quality findings 3

Ensure functions have docstrings for documentation
missing-docstring
def initialize_agent(
Avoid unnecessary list conversions; use generators where possible
unnecessary-list
tags_ = list(tags) if tags else []
Overuse may indicate design issues; consider polymorphism
isinstance-overuse
tags_.append(agent.value if isinstance(agent, AgentType) else agent)

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.