Created
October 9, 2023 13:15
-
-
Save bjoerntx/111daf479629402d6d3800c935c97ce9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[HttpPost] | |
public string PromptRequest([FromBody] ChatGPTRequest request) | |
{ | |
var htmlSuffix = ". Create the results in formatted HTML format with h1, p and li elements."; | |
// Remove a trailing full stop, if present | |
if (request.Text.EndsWith(".")) | |
{ | |
request.Text = request.Text.TrimEnd('.'); | |
} | |
HttpClient client = new HttpClient | |
{ | |
DefaultRequestHeaders = | |
{ | |
Authorization = new AuthenticationHeaderValue("Bearer", Models.Constants.OPENAI_API_KEY) | |
} | |
}; | |
Request apiRequest = new Request | |
{ | |
Messages = new[] | |
{ | |
new RequestMessage | |
{ | |
Role = "system", | |
Content = "You are a helpful assistant." | |
}, | |
new RequestMessage | |
{ | |
Role = "user", | |
Content = request.Text + htmlSuffix | |
} | |
} | |
}; | |
StringContent content = new StringContent( | |
System.Text.Json.JsonSerializer.Serialize(apiRequest), | |
Encoding.UTF8, | |
"application/json" | |
); | |
HttpResponseMessage httpResponseMessage = client.PostAsync( | |
"https://api.openai.com/v1/chat/completions", | |
content | |
).Result; | |
if (httpResponseMessage.IsSuccessStatusCode) | |
{ | |
Response response = System.Text.Json.JsonSerializer.Deserialize<Response>( | |
httpResponseMessage.Content.ReadAsStringAsync().Result | |
); | |
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(response.Choices[0].Message.Content); | |
return System.Convert.ToBase64String(plainTextBytes); | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment