from langchain.agents import create_agent

def get_weather(city: str) -> str:
    """获取指定城市的天气"""
    return f"{city} 天气总是晴朗!"

agent = create_agent(
    model="anthropic:claude-sonnet-4-5",
    tools=[get_weather],
    system_prompt="你是一个乐于助人的助手",
)

# 执行代理
agent.invoke(
    {"messages": [{"role": "user", "content": "旧金山天气如何?"}]}
)
  • 在 Python 开发中,使用 LangChain 时,执行上述代码时,出现如下错误信息
D:\PythonCode\LangChainTest\.venv\Scripts\python.exe D:\PythonCode\LangChainTest\main.py 
D:\PythonCode\LangChainTest\.venv\Lib\site-packages\langchain_core\_api\deprecation.py:26: UserWarning: Core Pydantic V1 functionality isn't compatible with Python 3.14 or greater.
  from pydantic.v1.fields import FieldInfo as FieldInfoV1
Traceback (most recent call last):
  File "D:\PythonCode\LangChainTest\main.py", line 7, in <module>
    agent = create_agent(
        model="anthropic:claude-sonnet-4-5",
        tools=[get_weather],
        system_prompt="你是一个乐于助人的助手",
    )
  File "D:\PythonCode\LangChainTest\.venv\Lib\site-packages\langchain\agents\factory.py", line 686, in create_agent
    model = init_chat_model(model)
  File "D:\PythonCode\LangChainTest\.venv\Lib\site-packages\langchain\chat_models\base.py", line 316, in init_chat_model
    return _init_chat_model_helper(
        cast("str", model),
        model_provider=model_provider,
        **kwargs,
    )
  File "D:\PythonCode\LangChainTest\.venv\Lib\site-packages\langchain\chat_models\base.py", line 345, in _init_chat_model_helper
    _check_pkg("langchain_anthropic")
    ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\PythonCode\LangChainTest\.venv\Lib\site-packages\langchain\chat_models\base.py", line 533, in _check_pkg
    raise ImportError(msg)
ImportError: Unable to import langchain_anthropic. Please install with `pip install -U langchain-anthropic`

Process finished with exit code 1
问题原因
  • 这个错误信息表示 LangChain 需要相应的模型包来调用 Anthropic 模型
处理策略
  • 安装必要的模型包
pip install langchain-anthropic
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐