强制使用流式输出

本节内容参考CaseStudy目录下的文件"LLMCaller.Table"的窗口"流式输出"。

你平时使用各种大模型进行对话的时候,之所以有打字效果,是因为大模型启用了SSE流格式输出内容,每个片段输出大概两到三个字符。

要强制大模型使用流式输出,需要:

1、需将LLMCaller的stream属性设置为true,大模型接口就会启用SSE流分片返回数据;若为false则一次性返回全部数据。

2、需使用GetResultAsync函数发起异步请求。

3、需定义一个回调函数,用于处理接收到分片数据,并将其赋值给LLMCaller的
SSEStreamHandler属性。

LLMCaller每收到一个分片数据,就会调用这个回调函数执行任务(通常是刷新UI)。

这个回调函数的类型为
Action(Of String, String),包括两个String型参数:

回调函数一般使用lamda函数定义,关于lambda函数的定义和注意事项,参考:lambda函数

内容类型有三种:

重要提示:

即使强制大模型使用流式输出,LLMCaller的Result(或ResultJObject)都会正常返回全部数据,回调函数作用通常仅限于刷新界面,实现打字效果,而不是获取数据。

示例

下面是一个流式输出的简单示例,可以在命令窗口执行:

'''Async
'
定义三个StringBuilder用于接收不同类型的数据片段,实际开发的时候可以将StringBuilder替换为显示内容的控件
Dim
answers As New StringBuilder()
Dim
thinks As New StringBuilder()
Dim
errors As New StringBuilder()
'
定义一个回调函数用于接收流式输出分片内容,这里按内容类型分别存储在三个StringBuilder中
Dim
chunkHandler As Action(Of String, String) =
Sub
(ttype As String, tcontent As String)
   
Select Case ttype
       
Case "think"
            thinks.Append(tcontent)
       
Case "answer"
            answers.Append(tcontent)
       
Case "error"
            errors.Append(tcontent)
   
End Select
End
Sub
'
发起访问
Dim
caller As New LLMCaller("https://api.deepseek.com/chat/completions", "deepseek-flash", "sk-a734b83536da45e9aedc3e42605bfb3a")
caller.SystemPrompt =
"你是一个唐朝诗人"
caller.UserMessage =
"请写一首睹月思人的诗"
caller.stream =
True
caller.SSEStreamHandler = chunkHandler

If
Await caller.GetResultAsync() Then
    Output.Show(
"Result:" & vbcrlf & caller.Result)
    Output.Show(
"分片接收的答案:" & vbcrlf & answers.ToString())
    Output.Show(
"分片接收的推理过程:" & vbcrlf & thinks.ToString())
Else

    MessageBoxA.Show(caller.Error)

End
If 


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