You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用本地gpt-oss-20b模型运行LlamaIndex ReAct Agent时,async for语法报错的解决方法咨询

使用本地gpt-oss-20b模型运行LlamaIndex ReAct Agent时,async for语法报错的解决方法咨询

我完全懂你遇到的问题——文档里的示例直接写了async for,但在普通Python脚本里这么写确实会触发语法错误,这是因为异步循环必须放在异步函数内部执行。你猜的没错,解决方法就是把这段异步逻辑包装成一个异步函数,再用asyncio.run()来启动它,这是Python处理异步任务的标准方式。

下面是修改后的完整可运行代码,我把关键改动标出来了:

import torch
import asyncio  # 新增:导入Python异步标准库
from llama_index.llms.huggingface import HuggingFaceLLM
from llama_index.core.agent import ReActAgent
from llama_index.core.tools import FunctionTool
from llama_index.core.callbacks import CallbackManager, LlamaDebugHandler

# 加载本地模型(这部分你的原代码没问题)
llm = HuggingFaceLLM(
    model_name="../gpt-oss-20b-local",
    tokenizer_name="../gpt-oss-20b-local",
    device_map="auto",
    model_kwargs={"torch_dtype": torch.float16},
)

def multiply(a: int, b: int) -> int:
    """Multiply two integers and returns the result integer"""
    return a * b

multiply_tool = FunctionTool.from_defaults(fn=multiply)

# 设置Agent(这部分也保持不变)
llama_debug = LlamaDebugHandler(print_trace_on_end=True)
callback_manager = CallbackManager([llama_debug])
agent = ReActAgent.from_tools(
    [multiply_tool],
    llm=llm,
    verbose=True,
    callback_manager=callback_manager
)

# 新增:把异步逻辑封装到异步函数里
async def run_stream_chat():
    response = agent.stream_chat("What is 21 * 21?")
    handler = llama_debug.get_event_handler("stream_chat")
    # 现在async for在异步函数内部,不会再报错
    async for ev in handler.stream_events():
        print(ev)
        print("---")

# 脚本主入口:启动异步任务
if __name__ == "__main__":
    asyncio.run(run_stream_chat())

关键改动说明:

  • 新增导入asyncio库:这是Python处理异步IO的核心标准库
  • 封装异步函数run_stream_chat():把原来的stream_chat调用和async for循环都放到这个异步函数里
  • 用asyncio.run()启动:在脚本的主入口,通过这个方法来执行异步函数,这是普通Python脚本运行异步代码的标准姿势

文档里的示例之所以直接写async for,是因为很多时候这类代码是在Jupyter Notebook或者支持顶层异步执行的环境里运行的,但在普通.py脚本里必须用上述方式处理。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 08:23:02