我正在尝试从 azure openai api 返回流结果,谁能告诉我下面方法中的最后一行是否会返回完整内容,还是会错过未从 api 收到的内容。 。另外,这是从 Azure OpenAI SDK 流 api 返回流的正确方法吗?
public async Task<Stream> GetStreamResponse(CompletionsRequest rawAzureOpenAIRequest)
{
rawAzureOpenAIRequest = new CompletionsRequest();
rawAzureOpenAIRequest.ModelToUse = DefaultTextModelToUse;
CompletionsOptions optns = new CompletionsOptions();
optns.Prompts.Add("below is the summary of technical consultant role in software");
var azResponse = await _openAIRepository
.GetRawCompletionStreamingResponse(rawAzureOpenAIRequest.ModelToUse, optns,
canToken);
return azResponse.GetRawResponse().ContentStream;
}
下面是azure的方法描述,但我不清楚“没有内容的响应返回null”是什么意思。它是否指的是尚未获取的内容?
我找到了另一种使用 azure openai api 产生返回的方法,但它是批量产生的,并且没有按预期工作。
public async IAsyncEnumerable<string> GetStreamResponse(CompletionsRequest rawAzureOpenAIRequest)
{
rawAzureOpenAIRequest = new CompletionsRequest();
rawAzureOpenAIRequest.ModelToUse = DefaultTextModelToUse;
CompletionsOptions optns = new CompletionsOptions();
optns.Prompts.Add("below is the summary of technical consultant role in software");
var azResponse = await _openAIRepository.GetStreamingResponse(rawAzureOpenAIRequest.ModelToUse, optns,
canToken);
await foreach (var choice in azResponse.Value.GetChoicesStreaming())
{
await foreach (var message in choice.GetTextStreaming())
{
yield return message;
}
}
}
我尝试创建一个消费 api ,它似乎返回结果,但我认为使用方法 1 可能会丢失一些数据。
最佳答案
在第一种方法中,行 return
azResponse.GetRawResponse().ContentStream;
将返回从 Azure OpenAI API 获取的流。对于没有内容的响应,
ContentStream 属性
返回 null。
在 Azure OpenAI SDK 的上下文中,如果 API 响应没有任何要返回的内容,则 ContentStream 属性将为 null。它不是指尚未获取的内容。
- 对于第一种方法丢失的数据,可以在返回之前检查ContentStream是否为null。
处理 ContentStream 为 null 情况的 C# 代码。
public async Task<Stream> GetStreamResponse(CompletionsRequest rawAzureOpenAIRequest)
{
rawAzureOpenAIRequest = new CompletionsRequest();
rawAzureOpenAIRequest.ModelToUse = DefaultTextModelToUse;
CompletionsOptions optns = new CompletionsOptions();
optns.Prompts.Add("below is the summary of technical consultant role in software");
var azResponse = await _openAIRepository.GetRawCompletionStreamingResponse(rawAzureOpenAIRequest.ModelToUse, optns, canToken);
if (azResponse.GetRawResponse().ContentStream != null)
{
return azResponse.GetRawResponse().ContentStream;
}
throw new Exception("No content available from the API response.");
}
- 对于使用
IAsyncEnumerable
的第二种方法,它会批量给出结果,并在每条消息可用时返回该结果。
有关更多信息,请参阅azure-sdk-for-net/ResponseSamples.cs at main- GitHub和 Github Issue.
关于c# - 从azure openai sdk api返回流的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76271722/