openai-cookbook
openai-cookbook copied to clipboard
how to use C# with stream
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");

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.
This issue was closed because it has been stalled for 10 days with no activity.