-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAI.cs
More file actions
53 lines (43 loc) · 2.13 KB
/
AI.cs
File metadata and controls
53 lines (43 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System.Text;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
namespace NoteWorthy;
internal class AI
{
private static readonly string API_KEY = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("OPENAI_API_KEY environment variable is not set.");
public static async Task<string> GetResponseAsync(string prompt)
{
using HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", API_KEY);
var requestBody = $@"
{{
""model"": ""gpt-4"",
""messages"": [
{{ ""role"": ""system"", ""content"": ""You are a helpful assistant that provides clear and concise answers, acting as a search engine. Use [yellow]text[/] to highlight important info. Make sure you close the markup with the closing tag: [/] ONLY use square brackets if it's for markup; if a square bracket is necessary, use a curly brace instead NO MATTER WHAT."" }},
{{ ""role"": ""user"", ""content"": ""{EscapeQuotes(prompt)}"" }}
]
}}";
StringContent httpContent = new StringContent(requestBody, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("https://api.openai.com/v1/chat/completions", httpContent);
if (!response.IsSuccessStatusCode)
{
string errorContent = await response.Content.ReadAsStringAsync();
throw new HttpRequestException($"API request failed with status code {response.StatusCode}: {errorContent}");
}
string responseContent = await response.Content.ReadAsStringAsync();
string pattern = "\"content\": \"(.*?)\",";
Match match = Regex.Match(responseContent, pattern);
if (match.Success)
{
return match.Groups[1].Value.Replace("\\n", "\n").Replace("\\\"", "\"").Trim();
}
else
{
throw new Exception("Unable to parse the API response.");
}
}
private static string EscapeQuotes(string s)
{
return s.Replace("\"", "\\\"");
}
}