Langchain python版本 LLM 重要函数invoke,ainvoke,stream,astream,batch,abatch

invoke

python 复制代码
# 2.实例化模型
model = init_chat_model(
    model="qwen-plus",
    model_provider="openai",
    api_key=os.getenv("aliQwen-api"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)

# 构建消息列表
messages = [
    SystemMessage(content="你是一个法律助手,只回答法律问题,超出范围的统一回答,非法律问题无可奉告"),
    HumanMessage(content="简单介绍下广告法,一句话告知50字以内")
    #HumanMessage(content="2+3等于几?")
]

# 3.调用模型
response = model.invoke(messages)  # ainvoke
print(f"响应类型:{type(response)}")
# 打印结果
print(response.content)
print(response.content_blocks)

ainvoke

python 复制代码
# 2.实例化模型
model = init_chat_model(
    model="qwen-plus",
    model_provider="openai",
    api_key=os.getenv("aliQwen-api"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)
async def main():
    # 异步调用一条请求
    response = await model.ainvoke("解释一下LangChain是什么,简洁回答100字以内")
    print(f"响应类型:{type(response)}")
    print(response.content_blocks)
# 4.运行异步函数
if __name__ == "__main__":
    asyncio.run(main())
'''
LangChain 提供 ainvoke() 异步调用接口,用于在 异步环境(async/await) 中高效并行地执行模型推理。
它的核心作用是:让你同时调用多个模型请求而不阻塞主线程 ------ 特别适合大批量请求或 Web 服务场景(如 FastAPI)
'''

stream

python 复制代码
# 2.实例化模型
model = init_chat_model(
    model="qwen-plus",
    model_provider="openai",
    api_key=os.getenv("aliQwen-api"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)

# 构建消息列表
messages = [
    SystemMessage(content="你叫小问,是一个乐于助人的AI人工助手"),
    HumanMessage(content="你是谁")
]

# 3.流式调用大模型
response = model.stream(messages)
print(f"响应类型:{type(response)}")
# 流式打印结果
for chunk in response:
    # 刷新缓冲区 (无换行符,缓冲区未刷新,内容可能不会立即显示)
    print(chunk.content, end="",flush=True)
print("\n")

astream

python 复制代码
# 2.实例化模型
model = init_chat_model(
    model="qwen-plus",
    model_provider="openai",
    api_key=os.getenv("aliQwen-api"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)

# 构建消息列表
messages = [
    SystemMessage(content="你叫小问,是一个乐于助人的AI人工助手"),
    HumanMessage(content="你是谁")
]
# 3.异步流式调用大模型(定义异步函数)
async def async_stream_call():
    # astream 返回异步生成器,无需 await 修饰,直接赋值
    response = model.astream(messages)
    print(f"响应类型:{type(response)}") # 响应类型:<class 'async_generator'>

    # 异步遍历异步生成器(必须使用 async for,不可用普通 for)
    # 异步遍历异步生成器(必须使用 async for,不可用普通 for)
    # 异步遍历异步生成器(必须使用 async for,不可用普通 for)
    async for chunk in response:
        # 刷新缓冲区,实现流式打印(无换行、即时输出)
        print(chunk.content, end="", flush=True)
    print("\n")

# 4.运行异步函数
if __name__ == "__main__":
    asyncio.run(async_stream_call())

batch

python 复制代码
# 2.实例化模型
model = init_chat_model(
    model="qwen-plus",
    model_provider="openai",
    api_key=os.getenv("aliQwen-api"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)

# 问题列表
questions = [
    "什么是redis?简洁回答,字数控制在100以内",
    "Python的生成器是做什么的?简洁回答,字数控制在100以内",
    "解释一下Docker和Kubernetes的关系?简洁回答,字数控制在100以内"
]

# 批量调用大模型 model.batch()
response = model.batch(questions)
print(f"响应类型:{type(response)}")
print()
for q, r in zip(questions, response):
    print(f"问题:{q}\n回答:{r.content}\n")

abatch

python 复制代码
# 2.实例化模型
model = init_chat_model(
    model="qwen-plus",
    model_provider="openai",
    api_key=os.getenv("aliQwen-api"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
)

questions = [
    "什么是redis?简洁回答,字数控制在100以内",
    "Python的生成器是做什么的?简洁回答,字数控制在100以内",
    "解释一下Docker和Kubernetes的关系?简洁回答,字数控制在100以内"
]
# 3.异步批量调用大模型(定义异步函数封装异步操作)
# abatch() 是异步方法,需要基于 async/await 语法构建异步程序,并用 asyncio 驱动运行
async def async_batch_call():
    # 调用 model.abatch() 异步批量处理请求,需用 await 修饰(关键)
    response = await model.abatch(questions)
    print(f"响应类型:{type(response)}")
    # 遍历结果并格式化输出(与原来的同步版本格式一致)
    for q, r in zip(questions, response):
        print(f"问题:{q}\n回答:{r.content}\n")
# 4.运行异步函数
if __name__ == "__main__":
    asyncio.run(async_batch_call())
相关推荐
沙蒿同学2 小时前
当古诗词遇上 AI:从 38 万句诗词中取一个好名字
python·算法·架构
xxie1237942 小时前
Python装饰器与语法糖
开发语言·python
CClaris2 小时前
大模型量化从0到1(五):GPTQ 原理详解 + 从零量化一个真实大模型
人工智能·python·算法·机器学习
Railshiqian2 小时前
UserPickerActivity 内部逻辑分析
开发语言·python
一tiao咸鱼3 小时前
前端转 agent # 02 - FastAPI 框架入门与原理
前端·python
Yolo566Q3 小时前
Noah-MP陆面过程模型建模方法与站点、区域模拟实践技术应用
开发语言·python
肖永威4 小时前
麒麟 V10 编译 Python 3.11 依赖包缺失与版本冲突问题解决实录
运维·python·麒麟操作系统
Csvn4 小时前
Python 开发技巧 · 类型注解进阶 —— 从 `TypeVar` 到 `Protocol`,让类型检查真正帮你抓 bug
后端·python
大流星4 小时前
LangChainJS之Runnable(三)
javascript·langchain