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())
相关推荐
_itgo3 小时前
LangGraph 主要3 种核心模式
ai·langchain·langgraph
RSABLOCKCHAIN3 小时前
AI Agents in LangGraph-2
人工智能·python
WA内核拾荒者4 小时前
WhatsApp 账号异常检测的自动化告警系统设计
数据库·python·自动化
码流怪侠4 小时前
【GitHub】Bend:让 GPU 并行编程像写 Python 一样简单
python·github
2401_894915535 小时前
GEO 搜索优化完整源码从零部署:环境配置、集群搭建全流程
开发语言·python·tcp/ip·算法·unity
zhiSiBuYu05177 小时前
Python3 模块开发与应用实战指南
python
databook8 小时前
用方差阈值过滤掉“惰性特征”
python·机器学习·scikit-learn
Freak嵌入式8 小时前
MCU 低功耗模式解析:时钟门控、电源门控、深度休眠
人工智能·python·单片机·嵌入式硬件·开源·依赖倒置原则·micropython
weixin_BYSJ19879 小时前
springboot校园自习室管理小程序---附源码32142
java·javascript·spring boot·python·django·flask·php