异步访问API接口

大模型也需要思考时间,特别是深度思考的时候耗时更多。

我们可以异步访问AI接口,这样在等待AI思考的过程中可以继续进行其他工作。

如果要异步访问大模型API接口,只需用GetResultAsync方法 代替GetResult方法即可。

在 Foxtable 中使用异步方法时,脚本开头必须加上 '''Async 标记(三个单引号 + Async),告诉 Foxtable 这段代码包含异步操作。缺少这个标记,Await 会报错。


例如:

'''Async
Dim
caller As New LLMCaller("https://api.deepseek.com/chat/completions", "deepseek-flash", "sk-a734b83536da45e9aedc3e42605bfb3a")
caller.UserMessage =
"请写一首睹月思人的七言诗"
If
Await caller.GetResultAsync() Then  '异步发起访问请求,注意要配合Await使用
    MessageBoxA.Show(caller.Result)

Else

    MessageBoxA.Show(caller.Error)

End
If

异步执行不仅可以避免界面卡顿,还可以批量发起请求,同时执行多个AI任务,例如下面的代码同时写唐诗、宋词和元曲:

'''Async
Dim
caller1 As New LLMCaller("https://api.deepseek.com/chat/completions", "deepseek-flash", "sk-a734b83536da45e9aedc3e42605bfb3a")
Dim
caller2 As New LLMCaller("https://api.deepseek.com/chat/completions", "deepseek-flash", "sk-a734b83536da45e9aedc3e42605bfb3a")
Dim
caller3 As New LLMCaller("https://api.deepseek.com/chat/completions", "deepseek-flash", "sk-a734b83536da45e9aedc3e42605bfb3a") 
caller1.UserMessage =
"请写一首唐诗"
caller2.UserMessage =
"请写一首宋词"
caller3.UserMessage =
"请写一首元曲" 
Dim
t1 As Task(Of Boolean) = caller1.GetResultAsync()
Dim
t2 As Task(Of Boolean) = caller2.GetResultAsync()
Dim
t3 As Task(Of Boolean) = caller3.GetResultAsync()
Await
Task.WhenAll(t1, t2, t3) ' 三个请求同时进行,总耗时约等于最慢的那个 
If
t1.Result Then Output.Show("唐诗:" & caller1.Result)
If
t2.Result Then Output.Show("宋词:" & caller2.Result)
If
t3.Result Then Output.Show("元曲:" & caller3.Result)


本页地址:http://www.foxtable.com/webhelp/topics/7205.htm