当前位置: 首页 > article >正文

How to apply streaming in azure openai dotnet web application?

题意:"如何在 Azure OpenAI 的 .NET Web 应用程序中应用流式处理?"

问题背景:

I want to create a web api backend that stream openai completion responses.

"我想创建一个 Web API 后端,用于流式传输 OpenAI 的完成响应。"

How can I apply the following solution to a web api action in controller?

"如何将以下解决方案应用到控制器中的 Web API 操作?"

var client = new OpenAIClient(nonAzureOpenAIApiKey, new OpenAIClientOptions());
var chatCompletionsOptions = new ChatCompletionsOptions()
{
    DeploymentName = "gpt-3.5-turbo", // Use DeploymentName for "model" with non-Azure clients
    Messages =
    {
        new ChatRequestSystemMessage("You are a helpful assistant. You will talk like a pirate."),
        new ChatRequestUserMessage("Can you help me?"),
        new ChatRequestAssistantMessage("Arrrr! Of course, me hearty! What can I do for ye?"),
        new ChatRequestUserMessage("What's the best way to train a parrot?"),
    }
};

await foreach (StreamingChatCompletionsUpdate chatUpdate in client.GetChatCompletionsStreaming(chatCompletionsOptions))
{
    if (chatUpdate.Role.HasValue)
    {
        Console.Write($"{chatUpdate.Role.Value.ToString().ToUpperInvariant()}: ");
    }
    if (!string.IsNullOrEmpty(chatUpdate.ContentUpdate))
    {
        Console.Write(chatUpdate.ContentUpdate);
    }
}

问题解决:

You can simply wrap your code inside the controller

"您可以简单地将代码包裹在控制器内。"

using Microsoft.AspNetCore.Mvc;
using OpenAI;
using OpenAI.Chat;
using System.Collections.Generic;
using System.Threading.Tasks;

[ApiController]
[Route("[controller]")]
public class ChatController : ControllerBase
{
    [HttpGet]
    public async Task<ActionResult<List<string>>> GetChatCompletions()
    {
        var client = new OpenAIClient(nonAzureOpenAIApiKey, new OpenAIClientOptions());
        var chatCompletionsOptions = new ChatCompletionsOptions()
        {
            DeploymentName = "gpt-3.5-turbo",
            Messages =
            {
                new ChatRequestSystemMessage("You are a helpful assistant. You will talk like a pirate."),
                new ChatRequestUserMessage("Can you help me?"),
                new ChatRequestAssistantMessage("Arrrr! Of course, me hearty! What can I do for ye?"),
                new ChatRequestUserMessage("What's the best way to train a parrot?"),
            }
        };

        var responses = new List<string>();

        await foreach (StreamingChatCompletionsUpdate chatUpdate in client.GetChatCompletionsStreaming(chatCompletionsOptions))
        {
            if (chatUpdate.Role.HasValue)
            {
                responses.Add($"{chatUpdate.Role.Value.ToString().ToUpperInvariant()}: ");
            }
            if (!string.IsNullOrEmpty(chatUpdate.ContentUpdate))
            {
                responses.Add(chatUpdate.ContentUpdate);
            }
        }

        return Ok(responses);
    }
}

If you don't want to hardcode the message and pass that as a body then you can do something like this

"如果您不想将消息硬编码并作为主体传递,那么您可以这样做"

using Microsoft.AspNetCore.Mvc;
using OpenAI;
using OpenAI.Chat;
using System.Collections.Generic;
using System.Threading.Tasks;

[ApiController]
[Route("[controller]")]
public class ChatController : ControllerBase
{
    public class ChatRequest
    {
        public List<string> Messages { get; set; }
    }

    [HttpPost]
    public async Task<ActionResult<List<string>>> PostChatCompletions([FromBody] ChatRequest request)
    {
        var client = new OpenAIClient(nonAzureOpenAIApiKey, new OpenAIClientOptions());
        var chatCompletionsOptions = new ChatCompletionsOptions()
        {
            DeploymentName = "gpt-3.5-turbo",
            Messages = new List<ChatRequestMessage>()
        };

        foreach (var message in request.Messages)
        {
            chatCompletionsOptions.Messages.Add(new ChatRequestUserMessage(message));
        }

        var responses = new List<string>();

        await foreach (StreamingChatCompletionsUpdate chatUpdate in client.GetChatCompletionsStreaming(chatCompletionsOptions))
        {
            if (chatUpdate.Role.HasValue)
            {
                responses.Add($"{chatUpdate.Role.Value.ToString().ToUpperInvariant()}: ");
            }
            if (!string.IsNullOrEmpty(chatUpdate.ContentUpdate))
            {
                responses.Add(chatUpdate.ContentUpdate);
            }
        }

        return Ok(responses);
    }
}

Remember the above implementation of the API does not support streaming responses. It waits for all the chat completions to be received from the OpenAI API, then sends them all at once to the client.

"请记住,上述 API 实现不支持流式响应。它会等待从 OpenAI API 接收到所有聊天完成后,再将它们一次性发送给客户端。"

Streaming responses to the client as they are received from the OpenAI API would require a different approach. This could be achieved using Server-Sent Events (SSE) or a similar technology, but it's important to note that not all clients and network environments support these technologies.

"将从 OpenAI API 接收到的响应流式传输给客户端需要采用不同的方法。这可以通过使用服务器发送事件 (SSE) 或类似技术来实现,但需要注意的是,并非所有客户端和网络环境都支持这些技术。"

Here's a simplified example of how you could implement this using Server-Sent Events in ASP.NET Core:

"以下是一个使用服务器发送事件 (SSE) 在 ASP.NET Core 中实现此功能的简化示例:"

[HttpPost]
public async Task PostChatCompletions([FromBody] ChatRequest request)
{
    var client = new OpenAIClient(nonAzureOpenAIApiKey, new OpenAIClientOptions());
    var chatCompletionsOptions = new ChatCompletionsOptions()
    {
        DeploymentName = "gpt-3.5-turbo",
        Messages = new List<ChatRequestMessage>()
    };

    foreach (var message in request.Messages)
    {
        chatCompletionsOptions.Messages.Add(new ChatRequestUserMessage(message));
    }

    Response.Headers.Add("Content-Type", "text/event-stream");

    await foreach (StreamingChatCompletionsUpdate chatUpdate in client.GetChatCompletionsStreaming(chatCompletionsOptions))
    {
        if (chatUpdate.Role.HasValue)
        {
            await Response.WriteAsync($"data: {chatUpdate.Role.Value.ToString().ToUpperInvariant()}: \n\n");
        }
        if (!string.IsNullOrEmpty(chatUpdate.ContentUpdate))
        {
            await Response.WriteAsync($"data: {chatUpdate.ContentUpdate}\n\n");
        }
    }
}


http://www.kler.cn/a/292397.html

相关文章:

  • 如何在 Ubuntu 上 部署 OceanBase
  • 针对gitgitee的使用
  • 动态规划-背包问题——[模版]完全背包问题
  • 云原生周刊:Istio 1.24.0 正式发布
  • 【NLP】医学搜索Query相关性判断【阿里云:天池比赛】
  • C# Winform--SerialPort串口通讯(ASCII码发送)
  • 抖音无水印视频下载
  • SAP物料分类帐的前台操作
  • Arthas工具使用,分析线上问题好帮手
  • The Prompt Report 1
  • 《挑战极限,畅享精彩 ——韩星地带:逃脱任务 3 震撼来袭》
  • Pr:媒体浏览器
  • 【Linux】解锁系统编程奥秘,高效进程控制的实战技巧
  • 利用Go语言模拟实现Raft协议
  • ElasticSearch-Ingest Pipeline Painless Script
  • 前端代码注释风格 - CSS篇
  • 【Kubernetes知识点问答题】Pod
  • 2024跨境电商卖家寻增量,1688寻源通接口 也想做“主角”
  • 树莓派3B驱动ST7735(内核)(TODO)
  • C语言——插入排序
  • 文本匹配任务(下)
  • 红队攻防 | 利用GitLab nday实现帐户接管
  • 【2024数模国赛题目解析丨免费分享】
  • CompleteableFuture异步编程框架
  • [linux基础知识]创建新用户并使用该用户
  • 【2024数学建模国赛赛题解析已出】原创免费分享