openai-cookbook icon indicating copy to clipboard operation
openai-cookbook copied to clipboard

how to use C# with stream

Open LuckyForeverCross opened this issue 2 years ago • 1 comments
trafficstars

I want to use C# with stream args ,but i countn‘t get the right result. the result as one response.do you have a right solution?

  ChatModel chatModel = new ChatModel { Model = "gpt-3.5-turbo", Stream=true,Messages = new List<MessageItem> { new MessageItem { Role = "user", Content = "hello boy" } } };
        var request = JsonConvert.SerializeObject(chatModel);
        HttpContent httpContent = new StringContent(request);
        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", apiKey);
        var httpResponse =await httpClient.PostAsync(requestUrl, httpContent);
        Response.Headers.Add("Cache-Control", "no-cache");
        Response.Headers.Add("Content-Type", "text/event-stream");
        //await response.StartAsync();
        await Response.Body.FlushAsync();

        var stream = await httpResponse.Content.ReadAsStreamAsync();
        var reader = new StreamReader(stream);

        while (!reader.EndOfStream)
        {
            var line = await reader.ReadLineAsync();

            if (string.IsNullOrEmpty(line))
            {
                await Response.WriteAsync("\n");
            }
            else
            {
                await Response.WriteAsync($"{line}\n\n");
                await Response.Body.FlushAsync();
            }
        }
        var data = ServerSentEventData("这是关闭通知", DateTime.Now.Ticks.ToString(), "close");

LuckyForeverCross avatar Apr 15 '23 12:04 LuckyForeverCross

image

LuckyForeverCross avatar Apr 15 '23 12:04 LuckyForeverCross

This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 10 days.

github-actions[bot] avatar Sep 30 '23 01:09 github-actions[bot]

This issue was closed because it has been stalled for 10 days with no activity.

github-actions[bot] avatar Oct 11 '23 01:10 github-actions[bot]