Skip to content

Commit 4894847

Browse files
author
PHAN Xuan Quang
committed
Refactor to use Gemini.NET library for content generation
Refactored multiple files to use the Gemini.NET library for generating content and validating API keys. Updated request construction and response handling across various scopes. Removed `Generator.cs` and added `GeminiGenerator.cs` for similar functionality. Modified `index.js` for local development. Updated `Events.csproj` to include the new package and project references.
1 parent 6d16c86 commit 4894847

File tree

8 files changed

+146
-110
lines changed

8 files changed

+146
-110
lines changed

Diff for: EngAce.Api/Controllers/HealthcheckController.cs

+5-6
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,15 @@ public async Task<ActionResult<string>> Healthcheck()
2121
return Unauthorized("Invalid Access Key");
2222
}
2323

24-
try
24+
var isValidApiKey = await HealthcheckScope.Healthcheck(_accessKey);
25+
if (isValidApiKey)
2526
{
26-
var result = await HealthcheckScope.Healthcheck(_accessKey);
2727
_logger.LogInformation("Gemini API Key: {ApiKey}", _accessKey);
28-
29-
return Ok(result);
28+
return Ok(isValidApiKey);
3029
}
31-
catch (Exception ex)
30+
else
3231
{
33-
return Unauthorized(ex.Message);
32+
return Unauthorized("Invalid Access Key");
3433
}
3534
}
3635
}

Diff for: Events/ChatScope.cs

+57-83
Large diffs are not rendered by default.

Diff for: Events/Events.csproj

+5-1
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,13 @@
66
<Nullable>enable</Nullable>
77
</PropertyGroup>
88

9+
<ItemGroup>
10+
<PackageReference Include="Gemini.NET" Version="1.1.1" />
11+
</ItemGroup>
12+
913
<ItemGroup>
1014
<ProjectReference Include="..\Entities\Entities.csproj" />
11-
<ProjectReference Include="..\Gemini\Gemini.csproj" />
15+
<ProjectReference Include="..\Helper\Helper.csproj" />
1216
</ItemGroup>
1317

1418
</Project>

Diff for: Events/HealthcheckScope.cs

+7-4
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1-
namespace Events
1+
using Gemini.NET;
2+
3+
namespace Events
24
{
35
public static class HealthcheckScope
46
{
5-
public static async Task<string> Healthcheck(string apiKey)
7+
public static async Task<bool> Healthcheck(string apiKey)
68
{
7-
var prompt = "Say `I am Gemini` to me!";
8-
return await Gemini.Generator.GenerateContent(apiKey, "You are my helpful assistant", prompt, false, 10);
9+
var generator = new Generator(apiKey);
10+
11+
return await generator.IsValidApiKeyAsync();
912
}
1013
}
1114
}

Diff for: Events/QuizScope.cs

+38-9
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
using Entities;
22
using Entities.Enums;
3-
using Gemini;
3+
using Gemini.NET;
44
using Helper;
5-
using Newtonsoft.Json;
5+
using Helpers;
66
using System.Text;
77

88
namespace Events
@@ -163,13 +163,23 @@ private static async Task<List<Quiz>> GenerateQuizesForLessThan15(string apiKey,
163163
promptBuilder.AppendLine($"Generate a set of multiple-choice English questions consisting of {questionsCount} to {questionsCount + 5} questions related to the topic '{topic.Trim()}' for me to practice, the quiz should be of the types: {types}");
164164
promptBuilder.AppendLine();
165165
promptBuilder.AppendLine("The generated questions should be of the types:");
166-
foreach ( var type in quizzTypes )
166+
foreach (var type in quizzTypes)
167167
{
168168
promptBuilder.AppendLine($"- {GeneralHelper.GetEnumDescription(type)}");
169169
}
170170

171-
var response = await Generator.GenerateContent(apiKey, Instruction, promptBuilder.ToString(), true, 30);
172-
return [.. JsonConvert.DeserializeObject<List<Quiz>>(response)];
171+
var generator = new Generator(apiKey);
172+
173+
var apiRequest = new ApiRequestBuilder()
174+
.WithSystemInstruction(Instruction)
175+
.WithPrompt(promptBuilder.ToString())
176+
.WithDefaultGenerationConfig(0.3F, Models.Enums.ResponseMimeType.Json)
177+
.DisableAllSafetySettings()
178+
.Build();
179+
180+
var response = await generator.GenerateContentAsync(apiRequest);
181+
182+
return [.. JsonHelper.AsObject<List<Quiz>>(response.Result)];
173183
}
174184
catch
175185
{
@@ -195,9 +205,19 @@ private static async Task<List<Quiz>> GenerateQuizesByType(string apiKey, string
195205
promptBuilder.AppendLine();
196206
promptBuilder.AppendLine($"Generate a set of multiple-choice English questions consisting of {questionsCount} to {questionsCount + 5} questions related to the topic '{topic.Trim()}' for me to practice, the type of the questions must be: {type}");
197207

198-
var response = await Generator.GenerateContent(apiKey, Instruction, promptBuilder.ToString(), true, 40);
208+
var generator = new Generator(apiKey);
209+
210+
var apiRequest = new ApiRequestBuilder()
211+
.WithSystemInstruction(Instruction)
212+
.WithPrompt(promptBuilder.ToString())
213+
.WithDefaultGenerationConfig(1, Models.Enums.ResponseMimeType.Json)
214+
.DisableAllSafetySettings()
215+
.Build();
199216

200-
return JsonConvert.DeserializeObject<List<Quiz>>(response)
217+
//var response = await GeminiGenerator.GenerateContent(apiKey, Instruction, promptBuilder.ToString(), true, 40);
218+
var response = await generator.GenerateContentAsync(apiRequest);
219+
220+
return JsonHelper.AsObject<List<Quiz>>(response.Result)
201221
.Take(questionsCount)
202222
.Select(quiz =>
203223
{
@@ -240,8 +260,17 @@ public static async Task<List<string>> SuggestTopcis(string apiKey, EnglishLevel
240260
promptBuilder.AppendLine();
241261
promptBuilder.AppendLine("Make sure that each topic is unique, concise, and relevant for practicing English at different levels, especially intermediate to advanced.");
242262

243-
var response = await Generator.GenerateContent(apiKey, instruction, promptBuilder.ToString(), true, 75);
244-
return [.. JsonConvert.DeserializeObject<List<string>>(response)];
263+
var generator = new Generator(apiKey);
264+
265+
var apiRequest = new ApiRequestBuilder()
266+
.WithSystemInstruction(instruction)
267+
.WithPrompt(promptBuilder.ToString())
268+
.WithDefaultGenerationConfig(0.7F, Models.Enums.ResponseMimeType.Json)
269+
.DisableAllSafetySettings()
270+
.Build();
271+
272+
var response = await generator.GenerateContentAsync(apiRequest);
273+
return [.. JsonHelper.AsObject<List<string>>(response.Result)];
245274
}
246275

247276
private static string GetLevelDescription(EnglishLevel level)

Diff for: Events/ReviewScope.cs

+15-4
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
using Entities;
22
using Entities.Enums;
3-
using Gemini;
3+
using Gemini.NET;
44
using Helper;
5-
using Newtonsoft.Json;
5+
using Helpers;
6+
using Models.Enums;
67
using System.Text;
78

89
namespace Events
@@ -137,8 +138,18 @@ public static async Task<Comment> GenerateReview(string apiKey, EnglishLevel lev
137138
promptBuilder.AppendLine("## My writting for you to review: ");
138139
promptBuilder.AppendLine(content.Trim());
139140

140-
var result = await Generator.GenerateContent(apiKey, instructionBuilder.ToString(), promptBuilder.ToString(), true, 30, GenerativeModel.Gemini_20_Flash_Thinking);
141-
return JsonConvert.DeserializeObject<Comment>(result);
141+
var generator = new Generator(apiKey);
142+
143+
var apiRequest = new ApiRequestBuilder()
144+
.WithSystemInstruction(instructionBuilder.ToString())
145+
.WithPrompt(promptBuilder.ToString())
146+
.WithDefaultGenerationConfig(0.5F, ResponseMimeType.Json)
147+
.DisableAllSafetySettings()
148+
.Build();
149+
150+
var response = await generator.GenerateContentAsync(apiRequest, ModelVersion.Gemini_20_Flash_Thinking);
151+
152+
return JsonHelper.AsObject<Comment>(response.Result);
142153
}
143154
}
144155
}

Diff for: Events/SearchScope.cs

+18-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
using System.Text;
1+
using Gemini.NET;
2+
using Models.Enums;
3+
using System.Text;
24

35
namespace Events
46
{
@@ -117,7 +119,21 @@ Người dùng có thể nhập vào từ hoặc cụm từ tiếng Anh để tr
117119
promptBuilder.AppendLine($"- {context.Trim()}");
118120
}
119121

120-
return await Gemini.Generator.GenerateContent(apiKey, useEnglish ? instructionforEnglish : instructionforVietnamese, promptBuilder.ToString().Trim(), false, 50, Gemini.GenerativeModel.Gemini_20_Flash_Lite);
122+
var generator = new Generator(apiKey)
123+
.ExcludesSearchEntryPointFromResponse()
124+
.ExcludesGroundingDetailFromResponse();
125+
126+
var apiRequest = new ApiRequestBuilder()
127+
.WithSystemInstruction(useEnglish ? instructionforEnglish : instructionforVietnamese)
128+
.WithPrompt(promptBuilder.ToString())
129+
.WithDefaultGenerationConfig(0.5F)
130+
.DisableAllSafetySettings()
131+
.EnableGrounding()
132+
.Build();
133+
134+
var response = await generator.GenerateContentAsync(apiRequest, ModelVersion.Gemini_20_Flash);
135+
136+
return response.Result;
121137
}
122138
}
123139
}

Diff for: Gemini/Generator.cs renamed to Gemini/GeminiGenerator.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
namespace Gemini
88
{
9-
public static class Generator
9+
public static class GeminiGenerator
1010
{
1111
private static readonly HttpClient Client = new();
1212

0 commit comments

Comments
 (0)