-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathResearchService.cs
More file actions
159 lines (138 loc) · 5.53 KB
/
ResearchService.cs
File metadata and controls
159 lines (138 loc) · 5.53 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using System.ClientModel;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.AI;
using Microsoft.Agents.AI;
using OpenAI;
using OpenAI.Chat;
using NoteBookmark.Domain;
using Reka.SDK;
using System.Text;
namespace NoteBookmark.AIServices;
public class ResearchService
{
private readonly ILogger<ResearchService> _logger;
private readonly Func<Task<(string ApiKey, string BaseUrl, string ModelName)>> _settingsProvider;
private readonly HttpClient _client;
public ResearchService(
HttpClient client,
ILogger<ResearchService> logger,
Func<Task<(string ApiKey, string BaseUrl, string ModelName)>> settingsProvider)
{
_logger = logger;
_client = client;
_settingsProvider = settingsProvider;
}
public async Task<PostSuggestions> SearchSuggestionsAsync(SearchCriterias searchCriterias)
{
PostSuggestions suggestions = new PostSuggestions();
HttpResponseMessage? response = null;
try
{
var settings = await _settingsProvider();
var webSearch = new Dictionary<string, object>
{
["max_uses"] = 3
};
var allowedDomains = searchCriterias.GetSplittedAllowedDomains();
var blockedDomains = searchCriterias.GetSplittedBlockedDomains();
if (allowedDomains != null && allowedDomains.Length > 0)
{
webSearch["allowed_domains"] = allowedDomains;
}
else if (blockedDomains != null && blockedDomains.Length > 0)
{
webSearch["blocked_domains"] = blockedDomains;
}
var requestPayload = new
{
model = settings.ModelName,
messages = new[]
{
new
{
role = "user",
content = searchCriterias.GetSearchPrompt()
}
},
response_format = GetResponseFormat(),
research = new
{
web_search = webSearch
},
};
var jsonPayload = JsonSerializer.Serialize(requestPayload, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
// await SaveToFile("research_request", jsonPayload);
var endpoint = settings.BaseUrl.TrimEnd('/') + "/chat/completions";
using var request = new HttpRequestMessage(HttpMethod.Post, endpoint);
request.Headers.Add("Authorization", $"Bearer {settings.ApiKey}");
request.Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
response = await _client.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();
await SaveToFile("research_response", responseContent);
var rekaResponse = JsonSerializer.Deserialize<RekaResponse>(responseContent);
if (response.IsSuccessStatusCode)
{
suggestions = JsonSerializer.Deserialize<PostSuggestions>(rekaResponse!.Choices![0].Message!.Content!)!;
}
else
{
throw new Exception($"Request failed with status code: {response.StatusCode}. Response: {responseContent}");
}
}
catch (Exception ex)
{
_logger.LogError($"An error occurred while fetching research suggestions: {ex.Message}");
}
return suggestions;
}
private object GetResponseFormat()
{
return new
{
type = "json_schema",
json_schema = new
{
name = "post_suggestions",
schema = new
{
type = "object",
properties = new
{
suggestions = new
{
type = "array",
items = new
{
type = "object",
properties = new
{
title = new { type = "string" },
author = new { type = "string" },
summary = new { type = "string", maxLength = 100 },
publication_date = new { type = "string", format = "date" },
url = new { type = "string" }
},
required = new[] { "title", "summary", "url" }
}
}
},
required = new[] { "post_suggestions" }
}
}
};
}
private async Task SaveToFile(string prefix, string responseContent)
{
string datetime = DateTime.Now.ToString("yyyy-MM-dd_HH-mm");
string fileName = $"{prefix}_{datetime}.json";
string folderPath = "Data";
Directory.CreateDirectory(folderPath);
string filePath = Path.Combine(folderPath, fileName);
await File.WriteAllTextAsync(filePath, responseContent);
}
}