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())
相关推荐
阿enna8 分钟前
从误检和漏检出发改进YOLO26n:建立错误样本库
人工智能·python·深度学习·yolo·目标检测·机器学习·cnn
青少儿编程课堂12 分钟前
蓝桥杯真题解析:手链配色计数与波利亚定理(全国青少年信息素养大赛与电子学会软件编程考级)
c++·python·算法·bfs·信息学竞赛
曲径海盗21 分钟前
【Python 学习第 66 天】字典基础
python·学习笔记·编程入门
专注仿真1 小时前
仿真智能体训练:强化学习中的生存、任务、杀伤、能耗与规则惩罚算法详解与实战
python·算法·afsim智能体·仿真训练·afsim智能体训练
cpolar技术支持3 小时前
datetime.now() 和 datetime.now(timezone.utc) 混进 SQLite:零报错,读出来差 8 小时
python·sqlite·时间戳·datetime·时区
维爱智VR认知学能3 小时前
Python SQLite本地训练记录表迁移失败回滚与事务验证
数据库·python·单元测试·sqlite·软件工程
用户298698530144 小时前
使用 Python 替换 Word 文档文字:从全文到指定范围
python·api
Thanks_ks4 小时前
手写一个 LRU 缓存:哈希表与双向链表的组合设计
python·哈希表·lru·双向链表·ordereddict·命中率·哨兵节点
AI创界者15 小时前
Python 进阶实战(七十一章):研发效能度量、自动化质量门禁与工程规范落地实战
人工智能·python·aigc
yingjie11016 小时前
快榜GEO|官网 AI 可读性自查 12 项(附 Python 检测脚本)
开发语言·人工智能·python