模型

初始化模型

模型初始化有多重方式,可以是使用from langchain_openai import ChatOpenAI的形式创建,也可以使用init_chat_model的形式创建,目前推荐使用后者方式
使用init_chat_model前需要确保已经安装上了对应的库,例如模型使用openai的,则需要安装pip install langchain[openai]库.
使用方式

from lanchain.chat_model import init_chat_model

model = init_chat_model(
 model="gpt-5.4", # 模型名称,必填,对于部分常用的模型,其会自动判断由哪个服务商处理.
model_provider="openai", # 指定模型厂商,此时将不会根据model来自动判断
"configurable_fields":"any", # 允许在后期使用时覆盖的配置参数,例如在invoke时可以覆盖"max_token"这样的参数
"config_prefix":"first", # 主要是避免在多个模型场景下,在运行时修改配置文件,只想对某个模型生效时,可以添加此参数,例如在invoke时,只想修改当前model的max_token,则在invoke(..., config={"configurable":{"first_max_token":1024}})
)

单独的模型调用

  • 单个消息
print(model.invoke('你好').content) #   你好!有什么我可以帮助你的吗?
  • 消息列表调用
conversation = [
    {"role": "system", "content": "You are a helpful assistant that translates English to French."},
    {"role": "user", "content": "Translate: I love programming."},
    {"role": "assistant", "content": "J'adore la programmation."},
    {"role": "user", "content": "Translate: I love building applications."}
]

response = model.invoke(conversation)
print(response)  # AIMessage("J'adore créer des applications.")

工具调用

对于模型对象而言,其与agent在工具(函数)调用时的区别在于模型对象只会返回一些工具调用的参数,不会去执行,但是agent会自动执行工具.

from langchain.tools import tool


@tool
def get_weather(city:str)->str:
    """
    获取天气
    :param city:城市名称
    :return:
    """
    print("[get_weather] 输入的city是:", city)
    return "今天的天气是晴转多云"


model_with_tools = model.bind_tools([get_weather]) # 绑定工具,需要注意,此时会返回一个绑定了工具的模型
resp = model_with_tools.invoke("今天北京的天气如何?")
for tool_call in resp.tool_calls:
    print(f"工具:{tool_call['name']}")
    print(f"工具参数:{tool_call['args']}")

工具函数的执行

from langchain.messages import HumanMessage

messages = [HumanMessage("今天北京的天气如何")]

model_with_tools = model.bind_tools([get_weather])
resp = model_with_tools.invoke(messages)
messages.append(resp)
for tool_call in resp.tool_calls:
    if tool_call['name']=='get_weather':
        func = get_weather
    else:
        raise ValueError(f"未知的工具:{tool_call['name']}")
    resp = func.invoke(tool_call)
    messages.append(resp)

resp = model_with_tools.invoke(messages)
print(resp.content)

强制工具调用

model_with_tools = model.bind_tools([tool_1], tool_choice="any")

结构化输出

支持使用pydantic和typedict来定义结构化输出的模型

from typing import TypedDict, Annotated


class MyThing(TypedDict):
    city= Annotated[str, "城市名称"]
    date = Annotated[str, "日期, 格式形如:%Y-%m-%d"]
    thing = Annotated[str, "具体的事情"]

model_with_structure = model.with_structured_output(MyThing)        
resp = model_with_structure .invoke("今天是2026年5月26日,明天要去新加坡出差")
print(resp) # {'出差地点': '新加坡', '出差日期': '2026-05-27'}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容