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

LlamaIndex中async方法使用await报错及协程异常求助

解决方案

1. 解决SyntaxError: 'await' outside function错误

await关键字仅能在**异步函数(async def定义)**内部使用,或通过Python 3.7+推荐的asyncio.run()直接运行异步协程,无需手动管理事件循环。

2. 解决RuntimeError: coroutine raised StopIteration错误

该错误多因使用过时的事件循环API或旧版本LlamaIndex的异步逻辑兼容性问题导致。改用asyncio.run()可规避此类问题,同时确保依赖库为最新版本。

正确代码示例

import asyncio
from llama_index.core.evaluation import BatchEvalRunner

# 确保已完成 faithfulness_gpt4、relevancy_gpt4、vector_index、llm、qas 的初始化
runner = BatchEvalRunner(
    {"faithfulness": faithfulness_gpt4, "relevancy": relevancy_gpt4},
    workers=8,
)

# 定义异步执行函数
async def run_evaluation():
    eval_results = await runner.aevaluate_queries(
        vector_index.as_query_engine(llm=llm), queries=qas.questions
    )
    return eval_results

# 运行异步任务
eval_results = asyncio.run(run_evaluation())

额外检查项

  • 确认Python版本≥3.7,asyncio.run()为3.7及以上版本新增API
  • 升级LlamaIndex至最新稳定版:pip install --upgrade llama-index-core(若使用OpenAI模型,需同步升级llama-index-llms-openai)
  • 验证qas.questions为合法字符串列表,格式符合aevaluate_queries参数要求

内容的提问来源于stack exchange,提问作者LUSAQX

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 12:52:03