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())
相关推荐
智能体与具身智能6 小时前
TVA具身智能的概念、架构与应用(19)
人工智能·python·具身智能
2601_962294616 小时前
python中range函数怎么用
python·for循环·可迭代对象·range函数·整数列表
青 春 记 忆7 小时前
零基础入门python70:Docker Compose 编排完整后端
python·后端开发
新时代牛马7 小时前
字符设备驱动完整篇:从 cdev_add、file_operations 到chrdev_open 与排障
开发语言·python
白山编程大哥8 小时前
Java OutputStreamWriter 详解:从字符到字节的桥梁
java·开发语言·python
ToTensor9 小时前
DataGen——合成数据生成器:把一句任务描述变成可校验的训练数据
langchain·agent
落羽的落羽9 小时前
【AI】快速理解AI应用的相关名词概念
linux·c++·人工智能·python·计算机网络·算法
Chasing__Dreams9 小时前
大模型应用开发--13--RAG 查询优化策略
python
“AI国潮设计-小江”9 小时前
《Python实战 | SDXL大模型批量生成“英歌舞海浪”蛋糕IP,附核心Prompt控制代码与IP授权变现思路》
人工智能·python·prompt·aigc
znnnk10 小时前
【Python】GUI 开发从入门到实战(三):PyQt/PySide 进阶之路
开发语言·python·pyqt