Skip to content

Commit

Permalink
Assigning a API_KEY using model.ApiKey is not working #20
Browse files Browse the repository at this point in the history
  • Loading branch information
jochenkirstaetter committed Mar 29, 2024
1 parent 3950525 commit 5225629
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 23 deletions.
4 changes: 4 additions & 0 deletions src/Mscc.GenerativeAI/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- extend XML documentation

### Fixed

- Assigning a API_KEY using model.ApiKey is not working ([#20](https://github.com/mscraftsman/generative-ai/issues/20))

## 0.9.3

### Changed
Expand Down
59 changes: 37 additions & 22 deletions src/Mscc.GenerativeAI/GenerativeModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ public class GenerativeModel
private string _model;
private string? _apiKey;
private string? _accessToken;
private bool _useHeaderProjectId;
private string? _projectId;
private List<SafetySetting>? _safetySettings;
private GenerationConfig? _generationConfig;
Expand Down Expand Up @@ -123,53 +122,68 @@ private string Model
}

/// <summary>
/// Returns the name of the model.
/// Sets the API key to use for the request.
/// </summary>
/// <returns>Name of the model.</returns>
public string Name => _model;

/// <remarks>
/// The value can only be set or modified before the first request is made.
/// </remarks>
public string? ApiKey
{
set
{
_apiKey = value;
if (!string.IsNullOrEmpty(_apiKey))
{
if (!Client.DefaultRequestHeaders.Contains("x-goog-api-key"))
if (Client.DefaultRequestHeaders.Contains("x-goog-api-key"))
{
Client.DefaultRequestHeaders.Add("x-goog-api-key", _apiKey);
Client.DefaultRequestHeaders.Remove("x-goog-api-key");
}
Client.DefaultRequestHeaders.Add("x-goog-api-key", _apiKey);
}
}
}

public string? AccessToken
{
set
{
_accessToken = value;
if (value != null)
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
}
}

/// <summary>
/// Sets the project ID to use for the request.
/// </summary>
/// <remarks>
/// The value can only be set or modified before the first request is made.
/// </remarks>
public string? ProjectId
{
set
{
_projectId = value;
if (!string.IsNullOrEmpty(_projectId))
{
_useHeaderProjectId = Client.DefaultRequestHeaders.Contains("x-goog-user-project");
if (!_useHeaderProjectId)
if (Client.DefaultRequestHeaders.Contains("x-goog-user-project"))
{
Client.DefaultRequestHeaders.Add("x-goog-user-project", _projectId);
Client.DefaultRequestHeaders.Remove("x-goog-user-project");
}
_useHeaderProjectId = Client.DefaultRequestHeaders.Contains("x-goog-user-project");
Client.DefaultRequestHeaders.Add("x-goog-user-project", _projectId);
}
}
}

/// <summary>
/// Returns the name of the model.
/// </summary>
/// <returns>Name of the model.</returns>
public string Name => _model;

/// <summary>
/// Sets the access token to use for the request.
/// </summary>
public string? AccessToken
{
set
{
_accessToken = value;
if (value != null)
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
}
}

/// <summary>
/// Initializes a new instance of the <see cref="GenerativeModel"/> class.
/// The default constructor attempts to read <c>.env</c> file and environment variables.
Expand Down Expand Up @@ -433,6 +447,7 @@ public async Task<string> TransferOwnership(string model, string emailAddress)
/// <param name="request"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">Thrown when the <paramref name="request"/> is <see langword="null"/>.</exception>
/// <exception cref="HttpRequestException">Thrown when the request fails to execute.</exception>
public async Task<GenerateContentResponse> GenerateContent(GenerateContentRequest? request)
{
if (request == null) throw new ArgumentNullException(nameof(request));
Expand All @@ -443,7 +458,7 @@ public async Task<GenerateContentResponse> GenerateContent(GenerateContentReques

var url = ParseUrl(Url, Method);
string json = Serialize(request);
var payload = new StringContent(json, Encoding.UTF8, MediaType);
var payload = new StringContent(json, Encoding.UTF8, MediaType);
var response = await Client.PostAsync(url, payload);
response.EnsureSuccessStatusCode();

Expand Down
41 changes: 40 additions & 1 deletion tests/Mscc.GenerativeAI/GoogleAi_GeminiPro_Should.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public void Initialize_Default_Model()
model.Should().NotBeNull();
model.Name.Should().Be($"{expected.SanitizeModelName()}");
}

[Fact]
public void Initialize_Model()
{
Expand Down Expand Up @@ -243,6 +243,45 @@ public async void GenerateContent_WithEmptyPrompt_ThrowsArgumentNullException()
await Assert.ThrowsAsync<ArgumentNullException>(() => model.GenerateContent(prompt));
}

[Fact]
public async void GenerateContent_WithInvalidAPIKey_ChangingBeforeRequest()
{
// Arrange
var prompt = "Tell me 4 things about Taipei. Be short.";
var googleAI = new GoogleAI(apiKey: "WRONG_API_KEY");
var model = googleAI.GenerativeModel(model: Model.Gemini10Pro001);
model.ApiKey = fixture.ApiKey;

// Act
var response = await model.GenerateContent(prompt);

// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
output.WriteLine(response?.Text);
}

[Fact]
public async void GenerateContent_WithInvalidAPIKey_ChangingAfterRequest()
{
// Arrange
var prompt = "Tell me 4 things about Taipei. Be short.";
var googleAI = new GoogleAI(apiKey: "WRONG_API_KEY");
var model = googleAI.GenerativeModel(model: Model.Gemini10Pro001);
await Assert.ThrowsAsync<HttpRequestException>(() => model.GenerateContent(prompt));

// Act
model.ApiKey = fixture.ApiKey;
var response = await model.GenerateContent(prompt);

// Assert
response.Should().NotBeNull();
response.Candidates.Should().NotBeNull().And.HaveCount(1);
response.Text.Should().NotBeEmpty();
output.WriteLine(response?.Text);
}

[Fact]
public async void Generate_Content_MultiplePrompt()
{
Expand Down

0 comments on commit 5225629

Please sign in to comment.