Skip to content

Instantly share code, notes, and snippets.

@bjoerntx
Created October 9, 2023 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjoerntx/111daf479629402d6d3800c935c97ce9 to your computer and use it in GitHub Desktop.
Save bjoerntx/111daf479629402d6d3800c935c97ce9 to your computer and use it in GitHub Desktop.
[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