跳至内容

并发

在使用GenAI时,您的程序可能会处于空闲状态,等待从LLM返回的令牌。

await和async

JavaScript 通过 async functions 提供了出色的非阻塞异步 API 支持。

// takes a while
async function workM() { ... }
// let other threads work while this function is running
await work()

该功能在内联提示中被用来等待LLM结果或同时运行多个查询。

串行执行与并发执行

在这个示例中,我们使用await来"串行"运行每个LLM查询:

const poem = await prompt`write a poem`
const essay = await prompt`write an essay`

不过,我们可以'并发'运行所有查询来加快速度:

const [poem, essay] = await Promise.all(
prompt`write a poem`,
prompt`write an essay`
)

这种方法可行,但如果条目数量较多可能会出现问题,因为您会同时创建大量请求,很可能触及某些速率限制边界。 请注意,GenAIScript会自动限制对单个模型的并发请求数量,以防止这种情况发生。

Promise队列

promise队列提供了一种以有保证的并发限制来并发运行promise的方式,可以指定同时允许运行的数量。 与Promise.all的区别在于您需要将每个promise包装在一个函数中。

const queue = host.promiseQueue(3)
const res = await queue.all([
() => prompt`write a poem`
() => prompt`write an essay`
])

使用mapAll函数来遍历数组。

const queue = host.promiseQueue(3)
const summaries = await queue.mapAll(
env.files,
(file) => prompt`Summarize ${file}`
)