当前位置: 首页 > news >正文

【大模型】-LangChain--stream流式同步异步

文章目录

  • 1.同步stream流
  • 2.异步astream流
  • 3.异步astream流json输出
  • 4.异步事件astream_events流
  • 5.异步多线程

1.同步stream流

importosfromlangchain_community.chat_modelsimportChatTongyi os.environ["DASHSCOPE_API_KEY"]="sk-秘钥"llm=ChatTongyi(model="qwen-plus")chunks=[]forchunkinllm.stream(#stream同步,异步是astream"天空是什么颜色?"):chunks.append(chunk)print(chunk.content,end="|",flush=True)#print(StrOutputParser().parse(chunks))

2.异步astream流

importosimportasynciofromlangchain_core.output_parsersimportStrOutputParserfromlangchain_core.promptsimportChatPromptTemplate,HumanMessagePromptTemplatefromlangchain_community.chat_modelsimportChatTongyifromlangchain_core.messagesimportSystemMessage os.environ["DASHSCOPE_API_KEY"]="sk-秘钥"llm=ChatTongyi(model="qwen-plus")prompt=ChatPromptTemplate.from_template("给我讲一个{topic}的故事")output_parser=StrOutputParser()chain=prompt|llm|output_parserasyncdefasync_astream_chain():asyncforchunkinchain.astream({"topic":"干将"}):print(chunk,end="|",flush=True)asyncio.run(async_astream_chain())

3.异步astream流json输出

importosimportasynciofromlangchain_core.output_parsersimportStrOutputParser,JsonOutputParserfromlangchain_core.promptsimportChatPromptTemplate,HumanMessagePromptTemplatefromlangchain_community.chat_modelsimportChatTongyifromlangchain_core.messagesimportSystemMessage os.environ["DASHSCOPE_API_KEY"]="sk-秘钥"llm=ChatTongyi(model="qwen-plus")#prompt = ChatPromptTemplate.from_template("给我讲一个{topic}的故事")output_parser=JsonOutputParser()chain=llm|output_parserasyncdefasync_astream_chain():asyncforchunkinchain.astream("以JSON格式输出法国、西班牙和日本的国家和人口列表"):print(chunk,flush=True)asyncio.run(async_astream_chain())

4.异步事件astream_events流

importosimportasynciofromlangchain_core.output_parsersimportStrOutputParserfromlangchain_core.promptsimportChatPromptTemplate,HumanMessagePromptTemplatefromlangchain_community.chat_modelsimportChatTongyifromlangchain_core.messagesimportSystemMessage os.environ["DASHSCOPE_API_KEY"]="sk-秘钥"llm=ChatTongyi(model="qwen-plus")asyncdefasync_astream():events=[]asyncforeventinllm.astream_events("hello",version="v2"):events.append(event)print(events)asyncio.run(async_astream())""" 事件 [{ 'event': 'on_chat_model_start', 'data': { 'input': 'hello' }, 'name': 'ChatTongyi', 'tags': [], 'run_id': 'ef708116-49b9-4572-8860-9bcf04c304e9', 'metadata': { 'ls_provider': 'tongyi', 'ls_model_type': 'chat', 'ls_model_name': 'qwen-plus' }, 'parent_ids': [] }, { 'event': 'on_chat_model_stream', 'run_id': 'ef708116-49b9-4572-8860-9bcf04c304e9', 'name': 'ChatTongyi', 'tags': [], 'metadata': { 'ls_provider': 'tongyi', 'ls_model_type': 'chat', 'ls_model_name': 'qwen-plus' }, 'data': { 'chunk': AIMessageChunk(content = 'Hello', additional_kwargs = {}, response_metadata = {}, id = 'lc_run--ef708116-49b9-4572-8860-9bcf04c304e9') }, 'parent_ids': [] }, { 'event': 'on_chat_model_stream', 'run_id': 'ef708116-49b9-4572-8860-9bcf04c304e9', 'name': 'ChatTongyi', 'tags': [], 'metadata': { 'ls_provider': 'tongyi', 'ls_model_type': 'chat', 'ls_model_name': 'qwen-plus' }, 'data': { 'chunk': AIMessageChunk(content = '! How', additional_kwargs = {}, response_metadata = {}, id = 'lc_run--ef708116-49b9-4572-8860-9bcf04c304e9') }, 'parent_ids': [] }, { 'event': 'on_chat_model_stream', 'run_id': 'ef708116-49b9-4572-8860-9bcf04c304e9', 'name': 'ChatTongyi', 'tags': [], 'metadata': { 'ls_provider': 'tongyi', 'ls_model_type': 'chat', 'ls_model_name': 'qwen-plus' }, 'data': { 'chunk': AIMessageChunk(content = ' can I assist', additional_kwargs = {}, response_metadata = {}, id = 'lc_run--ef708116-49b9-4572-8860-9bcf04c304e9') }, 'parent_ids': [] }, { 'event': 'on_chat_model_stream', 'run_id': 'ef708116-49b9-4572-8860-9bcf04c304e9', 'name': 'ChatTongyi', 'tags': [], 'metadata': { 'ls_provider': 'tongyi', 'ls_model_type': 'chat', 'ls_model_name': 'qwen-plus' }, 'data': { 'chunk': AIMessageChunk(content = ' you today?', additional_kwargs = {}, response_metadata = {}, id = 'lc_run--ef708116-49b9-4572-8860-9bcf04c304e9') }, 'parent_ids': [] }, { 'event': 'on_chat_model_stream', 'run_id': 'ef708116-49b9-4572-8860-9bcf04c304e9', 'name': 'ChatTongyi', 'tags': [], 'metadata': { 'ls_provider': 'tongyi', 'ls_model_type': 'chat', 'ls_model_name': 'qwen-plus' }, 'data': { 'chunk': AIMessageChunk(content = ' 😊', additional_kwargs = {}, response_metadata = {}, id = 'lc_run--ef708116-49b9-4572-8860-9bcf04c304e9') }, 'parent_ids': [] }, { 'event': 'on_chat_model_stream', 'run_id': 'ef708116-49b9-4572-8860-9bcf04c304e9', 'name': 'ChatTongyi', 'tags': [], 'metadata': { 'ls_provider': 'tongyi', 'ls_model_type': 'chat', 'ls_model_name': 'qwen-plus' }, 'data': { 'chunk': AIMessageChunk(content = '', additional_kwargs = {}, response_metadata = { 'finish_reason': 'stop', 'request_id': '3952154f-a9f5-4b39-a3c5-6eb8c85a6213', 'token_usage': { 'input_tokens': 9, 'output_tokens': 11, 'total_tokens': 20, 'prompt_tokens_details': { 'cached_tokens': 0 } } }, id = 'lc_run--ef708116-49b9-4572-8860-9bcf04c304e9') }, 'parent_ids': [] }, { 'event': 'on_chat_model_stream', 'run_id': 'ef708116-49b9-4572-8860-9bcf04c304e9', 'name': 'ChatTongyi', 'tags': [], 'metadata': { 'ls_provider': 'tongyi', 'ls_model_type': 'chat', 'ls_model_name': 'qwen-plus' }, 'data': { 'chunk': AIMessageChunk(content = '', additional_kwargs = {}, response_metadata = {}, id = 'lc_run--ef708116-49b9-4572-8860-9bcf04c304e9', chunk_position = 'last') }, 'parent_ids': [] }, { 'event': 'on_chat_model_end', 'data': { 'output': AIMessageChunk(content = 'Hello! How can I assist you today? 😊', additional_kwargs = {}, response_metadata = { 'finish_reason': 'stop', 'request_id': '3952154f-a9f5-4b39-a3c5-6eb8c85a6213', 'token_usage': { 'input_tokens': 9, 'output_tokens': 11, 'total_tokens': 20, 'prompt_tokens_details': { 'cached_tokens': 0 } } }, id = 'lc_run--ef708116-49b9-4572-8860-9bcf04c304e9') }, 'run_id': 'ef708116-49b9-4572-8860-9bcf04c304e9', 'name': 'ChatTongyi', 'tags': [], 'metadata': { 'ls_provider': 'tongyi', 'ls_model_type': 'chat', 'ls_model_name': 'qwen-plus' }, 'parent_ids': [] }] """

5.异步多线程

await asyncio.gather(task1(), task2())

importosimportasynciofromlangchain_core.output_parsersimportStrOutputParserfromlangchain_core.promptsimportChatPromptTemplate,HumanMessagePromptTemplatefromlangchain_community.chat_modelsimportChatTongyifromlangchain_core.messagesimportSystemMessage os.environ["DASHSCOPE_API_KEY"]="sk-秘钥"llm=ChatTongyi(model="qwen-plus")asyncdeftask1():prompt=ChatPromptTemplate.from_template("给我讲一个{topic}的故事,100字")output_parser=StrOutputParser()chain=prompt|llm|output_parserasyncforchunkinchain.astream({"topic":"干将"}):print(chunk,end="|",flush=True)asyncdeftask2():prompt=ChatPromptTemplate.from_template("给我讲一个{topic}的故事,100字")output_parser=StrOutputParser()chain=prompt|llm|output_parserasyncforchunkinchain.astream({"topic":"秦始皇"}):print(chunk,end="|",flush=True)asyncdefmain():#同步调用# await task1()# await task2()# 异步awaitasyncio.gather(task1(),task2())asyncio.run(main())
http://www.cnnetsun.cn/news/51806.html

相关文章:

  • 兜兜英语每日短语:逃单篇
  • 计算机毕业设计springboot汽车智慧检修系统 基于SpringBoot的智能汽车故障预测与维修管理平台 融合IoT的SpringBoot车辆健康监测与维修决策系统
  • python3
  • 【3D图像技术分析与实现】Apple Vision Pro三维成像技术栈深度解析
  • 经典算法题详解之统计重复个数(三)
  • 移动应用开发实验室大一上考核
  • 云数据库服务(如AWS RDS)的优势和考虑因素?
  • 【设计模式|第四篇】适配器模式:让不兼容的接口协同工作
  • asgiref终极指南:高效解决Python异步通信难题
  • 医学影像深度学习知识点总结
  • 从零到一:自动化3D建模的免代码解决方案
  • Kali中生成被控端
  • 13、Linux 文本编辑与命令操作实用指南
  • 20、Linux 备份全攻略
  • 22、Debian系统管理与安全保障全解析
  • 32、Debian变体与基于Debian的其他操作系统
  • 50、无线传感器网络部署方案与加密算法研究
  • 51、无线传感器网络部署方案与LEACH协议优化研究
  • 54、垃圾邮件和即时通讯垃圾信息的分类与控制措施
  • 如何通过AutoGPT生成高质量技术博客为GPU算力引流
  • 多目标蜣螂优化算法NSDBO:微电网多目标优化调度的利器
  • 本研究基于分形纤维丛统一场论,构建了黑洞时空的几何模型,揭示了奇点消解、霍金辐射修正及信息守恒的新机制。该模型的优势在于将宏观时空的广义相对论效应与微观量子的分形特性实现了有机融合。
  • 好写作AI语言侦探:你的论文严谨性“隐形把关人”
  • 解放双手!钉钉智能打卡神器完全上手手册
  • DMXAPI全球模型API调用完全指南:从入门到精通
  • 告别“翻墙“烦恼:DMXAPI让Gemini-3-pro-thinking调用快如闪电
  • leetcode 744. Find Smallest Letter Greater Than Target 寻找比目标字母大的最小字母-耗时100%
  • Home Assistant通知系统:3步打造智能家居提醒中心
  • 学Simulink——机器人轨迹跟踪场景实例:基于Simulink的永磁同步电机笛卡尔空间圆弧轨迹跟踪仿真
  • 【毕业设计/课程设计】基于Java的高校学科竞赛平台的设计与实现/源码+论文+PPT+数据