PROWAREtech
.NET: Google Generative AI Library
Steps to add Generative AI to your project:
- Sign up for a Google's AI Studio account and ensure you can generate an API key. This key is required to access Google's Gemini generative AI.
- Add the code below into your .NET 8 or later C# project.
- Start sending requests to Gemini.
- Optionally, convert the Gemini text to HTML.
Overview
This is a C# implementation of a client library (originally the NuGet package Mscc.GenerativeAI) for interacting with Google's Generative AI APIs (particularly focusing on Gemini models). The library provides a comprehensive interface for making API calls to generate text, chat, embed content, and perform other AI-related tasks.
The code includes extensive model definitions and configurations, with support for various Gemini model versions (1.0, 1.5, etc.) and different specialized variants (Pro, Flash, Vision, etc.). It handles all the necessary HTTP requests, authentication, response parsing, and provides strongly-typed classes for working with the API responses and data structures.
The library offers sophisticated features like token counting, safety settings, content filtering, function calling, chat session management, and support for different types of content including text, images, and code. It also includes robust error handling, retry logic, and configuration options for timeouts and other API behaviors.
The implementation follows good software engineering practices with proper separation of concerns, extensive parameter validation, clean class hierarchies, and comprehensive enum definitions for various API states and options. The code uses modern C# features and requires .NET 8.0 or later, with dependencies on System.Text.Json for serialization and standard HTTP client libraries for API communication.
Example Usage
namespace GenerativeAIConsole
{
internal class Program
{
static void Main(string[] args)
{
while (true)
{
Console.Write("Enter question: ");
var line = Console.ReadLine();
if (line == null || line.Length == 0)
break;
try
{
var apiKey = "ENTER_API_KEY_HERE";
var model = new ML.GenAI.GenerativeModel() { ApiKey = apiKey, Model = ML.GenAI.Model.GeminiPro };
var response = model.GenerateContent(line).Result;
string text = string.IsNullOrEmpty(response.Text) ? "**no response**" : response.Text;
Console.WriteLine(text);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
ML.GenAI Code
Over 4,000 lines of code without comments! This will be compiled into your executable.
// GenerativeAI.cs
// Requires .NET 8.0 or later
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ML.GenAI
{
public static class Model
{
public const string GeminiPro = "gemini-pro";
public const string Gemini10Pro = "gemini-1.0-pro";
public const string Gemini10Pro001 = "gemini-1.0-pro-001";
public const string Gemini10Pro002 = "gemini-1.0-pro-002";
public const string Gemini10ProTuning = "gemini-1.0-pro-001";
public const string GeminiProLatest = "gemini-1.0-pro-latest";
public const string GeminiProVision = "gemini-pro-vision";
public const string Gemini10ProVision = "gemini-1.0-pro-vision";
public const string Gemini10ProVision001 = "gemini-1.0-pro-vision-001";
public const string GeminiProVisionLatest = "gemini-1.0-pro-vision-latest";
public const string GeminiUltra = "gemini-ultra";
public const string GeminiUltraLatest = "gemini-1.0-ultra-latest";
public const string Gemini15Pro = "gemini-1.5-pro";
public const string Gemini15Pro001 = "gemini-1.5-pro-001";
public const string Gemini15Pro002 = "gemini-1.5-pro-002";
public const string Gemini15ProTuning = "gemini-1.5-pro-002";
public const string Gemini15ProPreview = "gemini-1.5-pro-preview-0409";
public const string Gemini15ProExperimental0801 = "gemini-1.5-pro-exp-0801";
public const string Gemini15ProExperimental0827 = "gemini-1.5-pro-exp-0827";
public const string Gemini15ProExperimental = "gemini-1.5-pro-exp-0827";
public const string Gemini15ProLatest = "gemini-1.5-pro-latest";
public const string Gemini15Flash = "gemini-1.5-flash";
public const string Gemini15FlashLatest = "gemini-1.5-flash-latest";
public const string Gemini15Flash001 = "gemini-1.5-flash-001";
public const string Gemini15Flash002 = "gemini-1.5-flash-002";
public const string Gemini15Flash001Tuning = "gemini-1.5-flash-001-tuning";
public const string Gemini15FlashTuning = "gemini-1.5-flash-001-tuning";
public const string Gemini15Flash8B = "gemini-1.5-flash-8b-001";
public const string Gemini15FlashExperimental0827 = "gemini-1.5-flash-exp-0827";
public const string Gemini15FlashExperimental0827_8B = "gemini-1.5-flash-8b-exp-0827";
public const string Gemini15FlashExperimental0924_8B = "gemini-1.5-flash-8b-exp-0924";
public const string BisonText001 = "text-bison-001";
public const string BisonText002 = "text-bison-002";
public const string BisonText = "text-bison-001";
public const string BisonText32k002 = "text-bison-32k-002";
public const string BisonText32k = "chat-bison-32k-002";
public const string UnicornText001 = "text-unicorn-001";
public const string UnicornText = "text-unicorn-001";
public const string BisonChat001 = "chat-bison-001";
public const string BisonChat002 = "chat-bison-002";
public const string BisonChat = "chat-bison-001";
public const string BisonChat32k002 = "chat-bison-32k-002";
public const string BisonChat32k = "chat-bison-32k-002";
public const string CodeBisonChat001 = "codechat-bison-001";
public const string CodeBisonChat002 = "codechat-bison-002";
public const string CodeBisonChat = "chat-bison-002";
public const string CodeBisonChat32k002 = "codechat-bison-32k-002";
public const string CodeBisonChat32k = "chat-bison-32k-002";
public const string CodeGecko001 = "code-gecko-001";
public const string CodeGecko002 = "code-gecko-002";
public const string CodeGeckoLatest = "code-gecko@latest";
public const string CodeGecko = "code-gecko@latest";
public const string GeckoEmbedding = "embedding-gecko-001";
public const string Embedding001 = "embedding-001";
public const string Embedding = "embedding-001";
public const string AttributedQuestionAnswering = "aqa";
public const string TextEmbedding004 = "text-embedding-004";
public const string TextEmbedding = "text-embedding-004";
public const string TextEmbeddingPreview0815 = "text-embedding-preview-0815";
public const string TextEmbeddingPreview = "text-embedding-preview-0815";
public const string TextMultilingualEmbedding = "text-multilingual-embedding-002";
public const string GeckoTextEmbedding001 = "textembedding-gecko@001";
public const string GeckoTextEmbedding003 = "textembedding-gecko@003";
public const string GeckoTextEmbedding = "textembedding-gecko@003";
public const string GeckoTextMultilingualEmbedding001 = "textembedding-gecko-multilingual@001";
public const string GeckoTextMultilingualEmbedding = "textembedding-gecko-multilingual@001";
public const string MultimodalEmbedding001 = "multimodalembedding@001";
public const string MultimodalEmbedding = "multimodalembedding@001";
public const string Imagen3 = "imagen-3.0-generate-001";
public const string Imagen3Fast = "imagen-3.0-fast-generate-001";
public const string ImageGeneration3 = "imagen-3.0-generate-0611";
public const string ImageGeneration3Fast = "imagen-3.0-fast-generate-0611";
public const string ImageGeneration006 = "imagegeneration@006";
public const string ImageGeneration005 = "imagegeneration@005";
public const string Imagen2 = "imagegeneration@006";
public const string ImageGeneration002 = "imagegeneration@002";
public const string Imagen = "imagegeneration@002";
public const string ImageGeneration = "imagegeneration@006";
public const string ImageText001 = "imagetext@001";
public const string ImageText = "imagetext@001";
}
public abstract class BaseModel
{
protected readonly string _publisher = "google";
protected readonly JsonSerializerOptions _options;
protected string _model;
protected string? _apiKey;
protected string? _accessToken;
protected string? _projectId;
protected string _region = "us-central1";
protected string? _endpointId;
protected static readonly Version _httpVersion = HttpVersion.Version11;
protected static readonly HttpClient Client = new HttpClient(new SocketsHttpHandler
{
PooledConnectionLifetime = TimeSpan.FromMinutes(30.0),
EnableMultipleHttp2Connections = true
})
{
DefaultRequestVersion = _httpVersion,
DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrHigher
};
protected virtual string Version => "v1";
public string Model
{
get
{
return _model;
}
set
{
_model = value.SanitizeModelName();
}
}
public string Name => _model;
public string? ApiKey
{
set
{
_apiKey = value;
if (!string.IsNullOrEmpty(_apiKey))
{
if (Client.DefaultRequestHeaders.Contains("x-goog-api-key"))
{
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);
}
}
}
public string? ProjectId
{
set
{
_projectId = value;
if (!string.IsNullOrEmpty(_projectId))
{
if (Client.DefaultRequestHeaders.Contains("x-goog-user-project"))
{
Client.DefaultRequestHeaders.Remove("x-goog-user-project");
}
Client.DefaultRequestHeaders.Add("x-goog-user-project", _projectId);
}
}
}
public string Region
{
get
{
return _region;
}
set
{
_region = value;
}
}
public TimeSpan Timeout
{
get
{
return Client.Timeout;
}
set
{
Client.Timeout = value;
}
}
protected virtual void ThrowIfUnsupportedRequest<T>(T request)
{
}
public BaseModel()
{
_options = DefaultJsonSerializerOptions();
GenerativeAIExtensions.ReadDotEnv();
ApiKey = Environment.GetEnvironmentVariable("GOOGLE_API_KEY");
AccessToken = Environment.GetEnvironmentVariable("GOOGLE_ACCESS_TOKEN");
Model = Environment.GetEnvironmentVariable("GOOGLE_AI_MODEL") ?? "gemini-1.5-pro";
_region = Environment.GetEnvironmentVariable("GOOGLE_REGION") ?? _region;
}
public BaseModel(string? projectId = null, string? region = null, string? model = null)
{
string credentialsFile = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS") ?? Environment.GetEnvironmentVariable("GOOGLE_WEB_CREDENTIALS") ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "gcloud", "application_default_credentials.json");
Credentials credentialsFromFile = GetCredentialsFromFile(credentialsFile);
AccessToken = _accessToken ?? GetAccessTokenFromAdc();
ProjectId = projectId ?? Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID") ?? credentialsFromFile?.ProjectId ?? _projectId;
_region = region ?? _region;
Model = model ?? _model;
}
protected string ParseUrl(string url, string method = "")
{
Dictionary<string, string> replacements = GetReplacements();
replacements.Add("method", method);
do
{
url = Regex.Replace(url, "\\{(?<name>.*?)\\}", (Match match) => (!replacements.TryGetValue(match.Groups["name"].Value, out string value)) ? "" : value);
}
while (url.Contains("{"));
return url;
Dictionary<string, string> GetReplacements()
{
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "BaseUrlGoogleAi", "https://generativelanguage.googleapis.com/{version}" },
{ "BaseUrlVertexAi", "https://{region}-aiplatform.googleapis.com/{version}/projects/{projectId}/locations/{region}" },
{ "version", Version },
{ "model", _model },
{
"apikey",
_apiKey ?? ""
},
{
"projectId",
_projectId ?? ""
},
{ "region", _region },
{ "location", _region },
{ "publisher", _publisher },
{ "endpointId", _endpointId }
};
}
}
protected string Serialize<T>(T request)
{
return JsonSerializer.Serialize(request, _options);
}
protected async Task<T> Deserialize<T>(HttpResponseMessage response)
{
await response.Content.ReadAsStringAsync();
return await response.Content.ReadFromJsonAsync<T>(_options);
}
private JsonSerializerOptions DefaultJsonSerializerOptions()
{
return new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
NumberHandling = JsonNumberHandling.AllowReadingFromString,
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
Converters = { (JsonConverter)new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseUpper) }
};
}
private Credentials? GetCredentialsFromFile(string credentialsFile)
{
Credentials result = null;
if (File.Exists(credentialsFile))
{
JsonSerializerOptions jsonSerializerOptions = DefaultJsonSerializerOptions();
jsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower;
using FileStream utf8Json = new FileStream(credentialsFile, FileMode.Open, FileAccess.Read);
result = JsonSerializer.Deserialize<Credentials>(utf8Json, jsonSerializerOptions);
}
return result;
}
private string GetAccessTokenFromAdc()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return RunExternalExe("cmd.exe", "/c gcloud auth application-default print-access-token").TrimEnd();
}
return RunExternalExe("gcloud", "auth application-default print-access-token").TrimEnd();
}
private string RunExternalExe(string filename, string arguments)
{
Process process = new Process();
StringBuilder stdOutput = new StringBuilder();
StringBuilder stdError = new StringBuilder();
process.StartInfo.FileName = filename;
if (!string.IsNullOrEmpty(arguments))
{
process.StartInfo.Arguments = arguments;
}
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += delegate (object sender, DataReceivedEventArgs args)
{
stdOutput.AppendLine(args.Data);
};
process.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs args)
{
stdError.AppendLine(args.Data);
};
try
{
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
}
catch (Exception ex)
{
return string.Empty;
}
if (process.ExitCode == 0)
{
return stdOutput.ToString();
}
StringBuilder stringBuilder = new StringBuilder();
if (stdError.Length > 0)
{
stringBuilder.AppendLine("Err output:");
stringBuilder.AppendLine(stdError.ToString());
}
if (stdOutput.Length != 0)
{
stringBuilder.AppendLine("Std output:");
stringBuilder.AppendLine(stdOutput.ToString());
}
throw new Exception(Format(filename, arguments) + " finished with exit code = " + process.ExitCode + ": " + stringBuilder);
}
private string Format(string filename, string? arguments)
{
return "'" + filename + (string.IsNullOrEmpty(arguments) ? string.Empty : (" " + arguments)) + "'";
}
}
public class GenerativeModel : BaseModel
{
private const string UrlGoogleAi = "{BaseUrlGoogleAi}/{model}:{method}";
private const string UrlVertexAi = "{BaseUrlVertexAi}/publishers/{publisher}/{model}:{method}";
private readonly bool _useVertexAi;
private readonly CachedContent? _cachedContent;
private readonly TuningJob? _tuningJob;
private readonly List<Tool> defaultGoogleSearchRetrieval;
private List<SafetySetting>? _safetySettings;
private GenerationConfig? _generationConfig;
private List<Tool>? _tools;
private ToolConfig? _toolConfig;
private Content? _systemInstruction;
private string Url
{
get
{
string result = "{BaseUrlGoogleAi}/{model}:{method}";
if (_useVertexAi)
{
result = "{BaseUrlVertexAi}/publishers/{publisher}/{model}:{method}";
if (!string.IsNullOrEmpty(_endpointId))
{
result = "{BaseUrlVertexAi}/{_endpointId}";
}
}
return result;
}
}
protected override string Version
{
get
{
if (_useVertexAi)
{
return "v1";
}
return "v1beta";
}
}
private string Method
{
get
{
switch (_model.SanitizeModelName().Split(new char[1] { '/' })[1])
{
case "chat-bison-001":
return ML.GenAI.Method.GenerateMessage;
case "text-bison-001":
return ML.GenAI.Method.GenerateText;
case "embedding-gecko-001":
return ML.GenAI.Method.EmbedText;
case "embedding-001":
return ML.GenAI.Method.EmbedContent;
case "text-embedding-004":
return ML.GenAI.Method.EmbedContent;
case "aqa":
return ML.GenAI.Method.GenerateAnswer;
default:
if (_useVertexAi)
{
if (!string.IsNullOrEmpty(_endpointId))
{
return ML.GenAI.Method.GenerateContent;
}
return ML.GenAI.Method.StreamGenerateContent;
}
return ML.GenAI.Method.GenerateContent;
}
}
}
internal bool IsVertexAI => _useVertexAi;
public bool UseServerSentEventsFormat { get; set; }
public bool UseJsonMode { get; set; }
public bool UseGrounding { get; set; }
protected override void ThrowIfUnsupportedRequest<T>(T request)
{
if (_cachedContent != null && UseGrounding)
{
throw new NotSupportedException("Grounding is not supported with CachedContent.");
}
if (UseJsonMode && UseGrounding)
{
throw new NotSupportedException("Grounding is not supported wit JSON mode.");
}
}
public GenerativeModel()
{
int num = 1;
List<Tool> list = new List<Tool>(num);
CollectionsMarshal.SetCount(list, num);
Span<Tool> span = CollectionsMarshal.AsSpan(list);
int num2 = 0;
span[num2] = new Tool
{
GoogleSearchRetrieval = new GoogleSearchRetrieval()
};
num2++;
defaultGoogleSearchRetrieval = list;
ProductInfoHeaderValue item = new ProductInfoHeaderValue(new ProductHeaderValue("ML.GenAI", Assembly.GetExecutingAssembly().GetName().Version?.ToString()));
BaseModel.Client.DefaultRequestHeaders.UserAgent.Add(item);
}
internal GenerativeModel(string? apiKey = null, string? model = null, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null, List<Tool>? tools = null, Content? systemInstruction = null, ToolConfig? toolConfig = null)
{
base.ApiKey = apiKey ?? _apiKey;
base.Model = model ?? _model;
if (_generationConfig == null)
{
_generationConfig = generationConfig;
}
if (_safetySettings == null)
{
_safetySettings = safetySettings;
}
if (_tools == null)
{
_tools = tools;
}
if (_toolConfig == null)
{
_toolConfig = toolConfig;
}
if (_systemInstruction == null)
{
_systemInstruction = systemInstruction;
}
}
internal GenerativeModel(string? projectId = null, string? region = null, string? model = null, string? endpoint = null, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null, List<Tool>? tools = null, Content? systemInstruction = null, ToolConfig? toolConfig = null)
{
int num = 1;
List<Tool> list = new List<Tool>(num);
CollectionsMarshal.SetCount(list, num);
Span<Tool> span = CollectionsMarshal.AsSpan(list);
int num2 = 0;
span[num2] = new Tool
{
GoogleSearchRetrieval = new GoogleSearchRetrieval()
};
num2++;
defaultGoogleSearchRetrieval = list;
_useVertexAi = true;
_endpointId = endpoint.SanitizeEndpointName();
_generationConfig = generationConfig;
_safetySettings = safetySettings;
_tools = tools;
_toolConfig = toolConfig;
_systemInstruction = systemInstruction;
}
internal GenerativeModel(CachedContent cachedContent, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null)
{
_cachedContent = cachedContent ?? throw new ArgumentNullException("cachedContent");
base.Model = cachedContent.Model;
_tools = cachedContent.Tools;
_toolConfig = cachedContent.ToolConfig;
_systemInstruction = cachedContent.SystemInstruction;
_generationConfig = generationConfig;
_safetySettings = safetySettings;
}
internal GenerativeModel(TuningJob tuningJob, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null)
{
_tuningJob = tuningJob ?? throw new ArgumentNullException("tuningJob");
_model = _tuningJob.TunedModel.Model;
_endpointId = _tuningJob.TunedModel.Endpoint.SanitizeEndpointName();
_generationConfig = generationConfig;
_safetySettings = safetySettings;
}
private async Task<List<ModelResponse>> ListTunedModels(int? pageSize = null, string? pageToken = null, string? filter = null)
{
if (_useVertexAi)
{
throw new NotSupportedException();
}
if (!string.IsNullOrEmpty(_apiKey))
{
throw new NotSupportedException("Accessing tuned models via API key is not provided. Setup OAuth for your project.");
}
string url = "{BaseUrlGoogleAi}/tunedModels";
Dictionary<string, string> queryStringParams = new Dictionary<string, string>
{
["pageSize"] = Convert.ToString(pageSize),
["pageToken"] = pageToken,
["filter"] = filter
};
url = ParseUrl(url).AddQueryString(queryStringParams);
HttpResponseMessage response = await BaseModel.Client.GetAsync(url);
response.EnsureSuccessStatusCode();
return (await Deserialize<ListTunedModelResponse>(response))?.TunedModels;
}
public async Task<List<ModelResponse>> ListModels(bool tuned = false, int? pageSize = 50, string? pageToken = null, string? filter = null)
{
if (tuned)
{
return await ListTunedModels(pageSize, pageToken, filter);
}
string url = "{BaseUrlGoogleAi}/models";
Dictionary<string, string> queryStringParams = new Dictionary<string, string>
{
["pageSize"] = Convert.ToString(pageSize),
["pageToken"] = pageToken
};
url = ParseUrl(url).AddQueryString(queryStringParams);
HttpResponseMessage response = await BaseModel.Client.GetAsync(url);
response.EnsureSuccessStatusCode();
return (await Deserialize<ListModelsResponse>(response))?.Models;
}
public async Task<ModelResponse> GetModel(string? model = null)
{
if (model == null)
{
model = _model;
}
model = model.SanitizeModelName();
if (!string.IsNullOrEmpty(_apiKey) && model.StartsWith("tunedModel", StringComparison.InvariantCultureIgnoreCase))
{
throw new NotSupportedException("Accessing tuned models via API key is not provided. Setup OAuth for your project.");
}
string url = "https://generativelanguage.googleapis.com/{version}/" + model;
url = ParseUrl(url);
HttpResponseMessage response = await BaseModel.Client.GetAsync(url);
response.EnsureSuccessStatusCode();
return await Deserialize<ModelResponse>(response);
}
public async Task<CreateTunedModelResponse> CreateTunedModel(ML.GenAI.CreateTunedModelRequest request)
{
if (!_model.Equals("text-bison-001".SanitizeModelName() ?? "", StringComparison.InvariantCultureIgnoreCase) && !_model.Equals("gemini-1.0-pro-001".SanitizeModelName() ?? "", StringComparison.InvariantCultureIgnoreCase))
{
throw new NotSupportedException();
}
if (!string.IsNullOrEmpty(_apiKey))
{
throw new NotSupportedException("Accessing tuned models via API key is not provided. Setup OAuth for your project.");
}
string tunedModels = ML.GenAI.Method.TunedModels;
string url = "{BaseUrlGoogleAi}/{method}";
url = ParseUrl(url, tunedModels);
StringContent content = new StringContent(Serialize(request), Encoding.UTF8, "application/json");
HttpResponseMessage response = await BaseModel.Client.PostAsync(url, content);
response.EnsureSuccessStatusCode();
return await Deserialize<CreateTunedModelResponse>(response);
}
public async Task<string> DeleteTunedModel(string model)
{
if (string.IsNullOrEmpty(model))
{
throw new ArgumentNullException("model");
}
model = model.SanitizeModelName();
if (!string.IsNullOrEmpty(_apiKey) && model.StartsWith("tunedModel", StringComparison.InvariantCultureIgnoreCase))
{
throw new NotSupportedException("Accessing tuned models via API key is not provided. Setup OAuth for your project.");
}
string url = "https://generativelanguage.googleapis.com/{version}/" + model;
url = ParseUrl(url);
HttpResponseMessage response = await BaseModel.Client.DeleteAsync(url);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public async Task<ModelResponse> UpdateTunedModel(string model, ModelResponse tunedModel, string? updateMask = null)
{
if (string.IsNullOrEmpty(model))
{
throw new ArgumentNullException("model");
}
model = model.SanitizeModelName();
if (!string.IsNullOrEmpty(_apiKey) && model.StartsWith("tunedModel", StringComparison.InvariantCultureIgnoreCase))
{
throw new NotSupportedException("Accessing tuned models via API key is not provided. Setup OAuth for your project.");
}
string url = "https://generativelanguage.googleapis.com/{version}/" + model;
Dictionary<string, string> queryStringParams = new Dictionary<string, string> { ["updateMask"] = updateMask };
url = ParseUrl(url).AddQueryString(queryStringParams);
StringContent content = new StringContent(Serialize(tunedModel), Encoding.UTF8, "application/json");
HttpResponseMessage response = await BaseModel.Client.PatchAsync(url, content);
response.EnsureSuccessStatusCode();
return await Deserialize<ModelResponse>(response);
}
public async Task<string> TransferOwnership(string model, string emailAddress)
{
if (string.IsNullOrEmpty(model))
{
throw new ArgumentNullException("model");
}
if (string.IsNullOrEmpty(emailAddress))
{
throw new ArgumentNullException("emailAddress");
}
model = model.SanitizeModelName();
if (!string.IsNullOrEmpty(_apiKey) && model.StartsWith("tunedModel", StringComparison.InvariantCultureIgnoreCase))
{
throw new NotSupportedException("Accessing tuned models via API key is not provided. Setup OAuth for your project.");
}
string transferOwnership = ML.GenAI.Method.TransferOwnership;
string requestUri = ParseUrl(Url, transferOwnership);
StringContent content = new StringContent(Serialize(new
{
EmailAddress = emailAddress
}), Encoding.UTF8, "application/json");
HttpResponseMessage response = await BaseModel.Client.PostAsync(requestUri, content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public async Task<GenerateContentResponse> GenerateContent(GenerateContentRequest? request, RequestOptions? requestOptions = null)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
ThrowIfUnsupportedRequest(request);
GenerateContentRequest generateContentRequest = request;
if (generateContentRequest.Tools == null)
{
generateContentRequest.Tools = _tools;
}
generateContentRequest = request;
if (generateContentRequest.ToolConfig == null)
{
generateContentRequest.ToolConfig = _toolConfig;
}
generateContentRequest = request;
if (generateContentRequest.SystemInstruction == null)
{
generateContentRequest.SystemInstruction = _systemInstruction;
}
if (_cachedContent != null)
{
request.CachedContent = _cachedContent.Name;
base.Model = _cachedContent.Model;
if (_cachedContent.Contents != null)
{
request.Contents.AddRange(_cachedContent.Contents);
}
request.Tools = null;
request.ToolConfig = null;
request.SystemInstruction = null;
}
request.Model = ((!string.IsNullOrEmpty(request.Model)) ? request.Model : _model);
generateContentRequest = request;
if (generateContentRequest.GenerationConfig == null)
{
generateContentRequest.GenerationConfig = _generationConfig;
}
generateContentRequest = request;
if (generateContentRequest.SafetySettings == null)
{
generateContentRequest.SafetySettings = _safetySettings;
}
if (UseJsonMode)
{
generateContentRequest = request;
if (generateContentRequest.GenerationConfig == null)
{
generateContentRequest.GenerationConfig = new GenerationConfig();
}
GenerationConfig generationConfig = request.GenerationConfig;
if (generationConfig.ResponseMimeType == null)
{
generationConfig.ResponseMimeType = "application/json";
}
}
if (UseGrounding)
{
generateContentRequest = request;
if (generateContentRequest.Tools == null)
{
generateContentRequest.Tools = defaultGoogleSearchRetrieval;
}
if (request.Tools != null && !request.Tools.Any((Tool t) => t.GoogleSearchRetrieval != null))
{
request.Tools = defaultGoogleSearchRetrieval;
}
}
string text = ParseUrl(Url, Method);
string text2 = Serialize(request);
StringContent content = new StringContent(text2, Encoding.UTF8, "application/json");
if (requestOptions != null)
{
BaseModel.Client.Timeout = requestOptions.Timeout;
}
HttpResponseMessage response = await BaseModel.Client.PostAsync(text, content);
response.EnsureSuccessStatusCode();
if (_useVertexAi)
{
StringBuilder fullText = new StringBuilder();
ML.GenAI.GroundingMetadata groundingMetadata = null;
List<GenerateContentResponse> list = await Deserialize<List<GenerateContentResponse>>(response);
foreach (GenerateContentResponse item in list)
{
if (item.Candidates?[0].GroundingMetadata != null)
{
groundingMetadata = item.Candidates[0].GroundingMetadata;
continue;
}
ML.GenAI.FinishReason? finishReason = item.Candidates?[0].FinishReason;
if (finishReason.HasValue && finishReason.GetValueOrDefault() == FinishReason.Safety)
{
return item;
}
fullText.Append(item.Text);
}
GenerateContentResponse generateContentResponse;
GenerateContentResponse generateContentResponse2 = (generateContentResponse = list.LastOrDefault());
if (generateContentResponse.Candidates == null)
{
generateContentResponse.Candidates = new List<Candidate>(1)
{
new Candidate
{
Content = new ContentResponse
{
Parts = new List<Part>(1)
{
new Part()
}
}
}
};
}
generateContentResponse2.Candidates[0].GroundingMetadata = groundingMetadata;
generateContentResponse2.Candidates[0].Content.Parts[0].Text = fullText.ToString();
return generateContentResponse2;
}
return await Deserialize<GenerateContentResponse>(response);
}
public async Task<GenerateContentResponse> GenerateContent(string? prompt, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null, List<Tool>? tools = null, ToolConfig? toolConfig = null, RequestOptions? requestOptions = null)
{
if (prompt == null)
{
throw new ArgumentNullException("prompt");
}
GenerateContentRequest request = new GenerateContentRequest(prompt, generationConfig ?? _generationConfig, safetySettings ?? _safetySettings, tools ?? _tools, null, toolConfig ?? _toolConfig);
return await GenerateContent(request, requestOptions);
}
public async Task<GenerateContentResponse> GenerateContent(List<IPart>? parts, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null, List<Tool>? tools = null, ToolConfig? toolConfig = null, RequestOptions? requestOptions = null)
{
if (parts == null)
{
throw new ArgumentNullException("parts");
}
GenerateContentRequest generateContentRequest = new GenerateContentRequest(parts, generationConfig ?? _generationConfig, safetySettings ?? _safetySettings, tools ?? _tools, null, toolConfig ?? _toolConfig);
generateContentRequest.Contents[0].Role = "user";
return await GenerateContent(generateContentRequest, requestOptions);
}
public async IAsyncEnumerable<GenerateContentResponse> GenerateContentStream(GenerateContentRequest? request, RequestOptions? requestOptions = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
{
if (request == null)
{
throw new ArgumentNullException("request");
}
ThrowIfUnsupportedRequest(request);
if (UseServerSentEventsFormat)
{
await foreach (GenerateContentResponse item in GenerateContentStreamSSE(request, requestOptions, cancellationToken))
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
yield return item;
}
yield break;
}
GenerateContentRequest generateContentRequest = request;
if (generateContentRequest.Tools == null)
{
generateContentRequest.Tools = _tools;
}
generateContentRequest = request;
if (generateContentRequest.ToolConfig == null)
{
generateContentRequest.ToolConfig = _toolConfig;
}
generateContentRequest = request;
if (generateContentRequest.SystemInstruction == null)
{
generateContentRequest.SystemInstruction = _systemInstruction;
}
if (_cachedContent != null)
{
request.CachedContent = _cachedContent.Name;
base.Model = _cachedContent.Model;
if (_cachedContent.Contents != null)
{
request.Contents.AddRange(_cachedContent.Contents);
}
request.Tools = null;
request.ToolConfig = null;
request.SystemInstruction = null;
}
request.Model = ((!string.IsNullOrEmpty(request.Model)) ? request.Model : _model);
generateContentRequest = request;
if (generateContentRequest.GenerationConfig == null)
{
generateContentRequest.GenerationConfig = _generationConfig;
}
generateContentRequest = request;
if (generateContentRequest.SafetySettings == null)
{
generateContentRequest.SafetySettings = _safetySettings;
}
if (UseJsonMode)
{
generateContentRequest = request;
if (generateContentRequest.GenerationConfig == null)
{
generateContentRequest.GenerationConfig = new GenerationConfig();
}
GenerationConfig generationConfig = request.GenerationConfig;
if (generationConfig.ResponseMimeType == null)
{
generationConfig.ResponseMimeType = "application/json";
}
}
if (UseGrounding)
{
generateContentRequest = request;
if (generateContentRequest.Tools == null)
{
generateContentRequest.Tools = defaultGoogleSearchRetrieval;
}
if (request.Tools != null && !request.Tools.Any((Tool t) => t.GoogleSearchRetrieval != null))
{
request.Tools = defaultGoogleSearchRetrieval;
}
}
string method = "streamGenerateContent";
string url = ParseUrl(Url, method);
MemoryStream ms = new MemoryStream();
await JsonSerializer.SerializeAsync(ms, request, _options, cancellationToken);
ms.Seek(0L, SeekOrigin.Begin);
HttpRequestMessage httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Version = BaseModel._httpVersion
};
httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using StreamContent payload = new StreamContent(ms);
httpRequestMessage.Content = payload;
payload.Headers.ContentType = new MediaTypeHeaderValue("application/json");
using HttpResponseMessage response = await BaseModel.Client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
response.EnsureSuccessStatusCode();
if (response.Content == null)
{
yield break;
}
using Stream stream = await response.Content.ReadAsStreamAsync();
await foreach (GenerateContentResponse item2 in JsonSerializer.DeserializeAsyncEnumerable<GenerateContentResponse>(stream, _options, cancellationToken))
{
if (cancellationToken.IsCancellationRequested)
{
break;
}
yield return item2;
}
}
public IAsyncEnumerable<GenerateContentResponse> GenerateContentStream(string? prompt, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null, List<Tool>? tools = null, ToolConfig? toolConfig = null, RequestOptions? requestOptions = null)
{
if (prompt == null)
{
throw new ArgumentNullException("prompt");
}
GenerateContentRequest request = new GenerateContentRequest(prompt, generationConfig ?? _generationConfig, safetySettings ?? _safetySettings, tools ?? _tools, null, toolConfig ?? _toolConfig);
return GenerateContentStream(request, requestOptions);
}
public IAsyncEnumerable<GenerateContentResponse> GenerateContentStream(List<IPart>? parts, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null, List<Tool>? tools = null, ToolConfig? toolConfig = null, RequestOptions? requestOptions = null)
{
if (parts == null)
{
throw new ArgumentNullException("parts");
}
GenerateContentRequest generateContentRequest = new GenerateContentRequest(parts, generationConfig ?? _generationConfig, safetySettings ?? _safetySettings, tools ?? _tools, null, toolConfig ?? _toolConfig);
generateContentRequest.Contents[0].Role = "user";
return GenerateContentStream(generateContentRequest, requestOptions);
}
internal async IAsyncEnumerable<GenerateContentResponse> GenerateContentStreamSSE(GenerateContentRequest? request, RequestOptions? requestOptions = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
{
if (request == null)
{
throw new ArgumentNullException("request");
}
GenerateContentRequest generateContentRequest = request;
if (generateContentRequest.Tools == null)
{
generateContentRequest.Tools = _tools;
}
generateContentRequest = request;
if (generateContentRequest.ToolConfig == null)
{
generateContentRequest.ToolConfig = _toolConfig;
}
generateContentRequest = request;
if (generateContentRequest.SystemInstruction == null)
{
generateContentRequest.SystemInstruction = _systemInstruction;
}
if (_cachedContent != null)
{
request.CachedContent = _cachedContent.Name;
base.Model = _cachedContent.Model;
if (_cachedContent.Contents != null)
{
request.Contents.AddRange(_cachedContent.Contents);
}
request.Tools = null;
request.ToolConfig = null;
request.SystemInstruction = null;
}
request.Model = ((!string.IsNullOrEmpty(request.Model)) ? request.Model : _model);
generateContentRequest = request;
if (generateContentRequest.GenerationConfig == null)
{
generateContentRequest.GenerationConfig = _generationConfig;
}
generateContentRequest = request;
if (generateContentRequest.SafetySettings == null)
{
generateContentRequest.SafetySettings = _safetySettings;
}
string method = "streamGenerateContent";
string uriString = ParseUrl(Url, method).AddQueryString(new Dictionary<string, string> { ["alt"] = "sse" });
StringContent content = new StringContent(Serialize(request), Encoding.UTF8, "application/json");
HttpRequestMessage httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
Content = content,
RequestUri = new Uri(uriString),
Version = BaseModel._httpVersion
};
httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using HttpResponseMessage response = await BaseModel.Client.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
response.EnsureSuccessStatusCode();
if (response.Content == null)
{
yield break;
}
using StreamReader sr = new StreamReader(await response.Content.ReadAsStreamAsync());
while (!sr.EndOfStream)
{
string text = await sr.ReadLineAsync();
if (!string.IsNullOrWhiteSpace(text))
{
GenerateContentResponse generateContentResponse = JsonSerializer.Deserialize<GenerateContentResponse>(text.Substring("data:".Length).Trim(), _options);
if (cancellationToken.IsCancellationRequested)
{
yield break;
}
yield return generateContentResponse;
}
}
}
public async Task<GenerateAnswerResponse> GenerateAnswer(GenerateAnswerRequest? request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
if (!_model.Equals("aqa".SanitizeModelName() ?? "", StringComparison.InvariantCultureIgnoreCase))
{
throw new NotSupportedException();
}
string requestUri = ParseUrl(Url, Method);
StringContent content = new StringContent(Serialize(request), Encoding.UTF8, "application/json");
HttpResponseMessage response = await BaseModel.Client.PostAsync(requestUri, content);
response.EnsureSuccessStatusCode();
return await Deserialize<GenerateAnswerResponse>(response);
}
public async Task<GenerateAnswerResponse> GenerateAnswer(string? prompt, AnswerStyle? answerStyle = null, List<SafetySetting>? safetySettings = null)
{
if (prompt == null)
{
throw new ArgumentNullException("prompt");
}
GenerateAnswerRequest request = new GenerateAnswerRequest(prompt, answerStyle, safetySettings ?? _safetySettings);
return await GenerateAnswer(request);
}
public async Task<EmbedContentResponse> EmbedContent(EmbedContentRequest request, string? model = null, TaskType? taskType = null, string? title = null)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
if (request.Content == null)
{
throw new ArgumentNullException("Content");
}
if (string.IsNullOrEmpty(request.Model))
{
request.Model = model ?? _model;
}
EmbedContentRequest embedContentRequest = request;
if (!embedContentRequest.TaskType.HasValue)
{
embedContentRequest.TaskType = taskType;
}
embedContentRequest = request;
if (embedContentRequest.Title == null)
{
embedContentRequest.Title = title;
}
if (!new string[2]
{
"embedding-001".SanitizeModelName(),
"text-embedding-004".SanitizeModelName()
}.Contains(request.Model.SanitizeModelName()))
{
throw new NotSupportedException();
}
if (!string.IsNullOrEmpty(request.Title) && request.TaskType.GetValueOrDefault() != TaskType.RetrievalDocument)
{
throw new NotSupportedException("If a title is specified, the task must be a retrieval document type task.");
}
string requestUri = ParseUrl(Url, Method);
StringContent content = new StringContent(Serialize(request), Encoding.UTF8, "application/json");
HttpResponseMessage response = await BaseModel.Client.PostAsync(requestUri, content);
response.EnsureSuccessStatusCode();
return await Deserialize<EmbedContentResponse>(response);
}
public async Task<EmbedContentResponse> EmbedContent(List<EmbedContentRequest> requests, string? model = null, TaskType? taskType = null, string? title = null)
{
if (requests == null)
{
throw new ArgumentNullException("requests");
}
if (!new string[2]
{
"embedding-001".SanitizeModelName(),
"text-embedding-004".SanitizeModelName()
}.Contains(_model.SanitizeModelName()))
{
throw new NotSupportedException();
}
if (!string.IsNullOrEmpty(title) && taskType.GetValueOrDefault() != TaskType.RetrievalDocument)
{
throw new NotSupportedException("If a title is specified, the task must be a retrieval document type task.");
}
string batchEmbedContents = ML.GenAI.Method.BatchEmbedContents;
string requestUri = ParseUrl(Url, batchEmbedContents);
StringContent content = new StringContent(Serialize(requests), Encoding.UTF8, "application/json");
return await Deserialize<EmbedContentResponse>(await BaseModel.Client.PostAsync(requestUri, content));
}
public async Task<EmbedContentResponse> EmbedContent(string content, string? model = null, TaskType? taskType = null, string? title = null)
{
if (content == null)
{
throw new ArgumentNullException("content");
}
EmbedContentRequest request = new EmbedContentRequest(content)
{
Model = model,
TaskType = taskType,
Title = title
};
return await EmbedContent(request);
}
public async Task<EmbedContentResponse> EmbedContent(IEnumerable<string> content, string? model = null, TaskType? taskType = null, string? title = null)
{
if (content == null)
{
throw new ArgumentNullException("content");
}
EmbedContentRequest embedContentRequest = new EmbedContentRequest
{
Model = model?.SanitizeModelName(),
Content = new ContentResponse(),
TaskType = taskType,
Title = title
};
foreach (string item in content)
{
if (!string.IsNullOrEmpty(item))
{
embedContentRequest.Content.Parts.Add(new Part
{
Text = item
});
}
}
return await EmbedContent(embedContentRequest);
}
public async Task<EmbedContentResponse> EmbedContent(ContentResponse content, string? model = null, TaskType? taskType = null, string? title = null)
{
if (content == null)
{
throw new ArgumentNullException("content");
}
EmbedContentRequest request = new EmbedContentRequest
{
Model = model,
Content = content,
TaskType = taskType,
Title = title
};
return await EmbedContent(request);
}
public async Task<CountTokensResponse> CountTokens(GenerateContentRequest? request, RequestOptions? requestOptions = null)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
string countTokens = ML.GenAI.Method.CountTokens;
string requestUri = ParseUrl(Url, countTokens);
StringContent content = new StringContent(Serialize(request), Encoding.UTF8, "application/json");
if (requestOptions != null)
{
BaseModel.Client.Timeout = requestOptions.Timeout;
}
HttpResponseMessage response = await BaseModel.Client.PostAsync(requestUri, content);
response.EnsureSuccessStatusCode();
return await Deserialize<CountTokensResponse>(response);
}
public async Task<CountTokensResponse> CountTokens(string? prompt, RequestOptions? requestOptions = null)
{
if (prompt == null)
{
throw new ArgumentNullException("prompt");
}
switch (_model.SanitizeModelName().Split(new char[1] { '/' })[1])
{
case "chat-bison-001":
{
GenerateMessageRequest request4 = new GenerateMessageRequest(prompt);
return await CountTokens(request4, requestOptions);
}
case "text-bison-001":
{
GenerateTextRequest request3 = new GenerateTextRequest(prompt);
return await CountTokens(request3, requestOptions);
}
case "embedding-gecko-001":
{
GenerateTextRequest request2 = new GenerateTextRequest(prompt);
return await CountTokens(request2, requestOptions);
}
default:
{
GenerateContentRequest request = new GenerateContentRequest(prompt, _generationConfig, _safetySettings, _tools);
return await CountTokens(request, requestOptions);
}
}
}
public async Task<CountTokensResponse> CountTokens(List<IPart>? parts)
{
if (parts == null)
{
throw new ArgumentNullException("parts");
}
GenerateContentRequest request = new GenerateContentRequest(parts, _generationConfig, _safetySettings, _tools);
return await CountTokens(request);
}
public async Task<CountTokensResponse> CountTokens(FileResource file)
{
if (file == null)
{
throw new ArgumentNullException("file");
}
GenerateContentRequest request = new GenerateContentRequest(file, _generationConfig, _safetySettings, _tools);
return await CountTokens(request);
}
public ChatSession StartChat(List<ContentResponse>? history = null, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null, List<Tool>? tools = null, bool enableAutomaticFunctionCalling = false)
{
GenerationConfig generationConfig2 = generationConfig ?? _generationConfig;
List<SafetySetting> safetySettings2 = safetySettings ?? _safetySettings;
List<Tool> tools2 = tools ?? _tools;
if (_cachedContent != null && history == null)
{
history = _cachedContent.Contents?.Select((Content c) => new ContentResponse
{
Role = c.Role,
Parts = c.PartTypes
}).ToList();
}
return new ChatSession(this, history, generationConfig2, safetySettings2, tools2, enableAutomaticFunctionCalling);
}
public async Task<PredictResponse> Predict(PredictRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
string predict = ML.GenAI.Method.Predict;
string requestUri = ParseUrl(Url, predict);
StringContent content = new StringContent(Serialize(request), Encoding.UTF8, "application/json");
HttpResponseMessage response = await BaseModel.Client.PostAsync(requestUri, content);
response.EnsureSuccessStatusCode();
return await Deserialize<PredictResponse>(response);
}
public async Task<Operation> PredictLongRunning(PredictLongRunningRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
string predictLongRunning = ML.GenAI.Method.PredictLongRunning;
string requestUri = ParseUrl(Url, predictLongRunning);
StringContent content = new StringContent(Serialize(request), Encoding.UTF8, "application/json");
HttpResponseMessage response = await BaseModel.Client.PostAsync(requestUri, content);
response.EnsureSuccessStatusCode();
return await Deserialize<Operation>(response);
}
public async Task<GenerateTextResponse> GenerateText(GenerateTextRequest? request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
if (!_model.Equals("text-bison-001".SanitizeModelName() ?? "", StringComparison.InvariantCultureIgnoreCase))
{
throw new NotSupportedException();
}
string requestUri = ParseUrl(Url, Method);
StringContent content = new StringContent(Serialize(request), Encoding.UTF8, "application/json");
HttpResponseMessage response = await BaseModel.Client.PostAsync(requestUri, content);
response.EnsureSuccessStatusCode();
return await Deserialize<GenerateTextResponse>(response);
}
public async Task<GenerateTextResponse> GenerateText(string prompt)
{
if (prompt == null)
{
throw new ArgumentNullException("prompt");
}
GenerateTextRequest request = new GenerateTextRequest(prompt);
return await GenerateText(request);
}
public async Task<CountTokensResponse> CountTokens(GenerateTextRequest? request, RequestOptions? requestOptions = null)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
string countTextTokens = ML.GenAI.Method.CountTextTokens;
string requestUri = ParseUrl(Url, countTextTokens);
StringContent content = new StringContent(Serialize(request), Encoding.UTF8, "application/json");
if (requestOptions != null)
{
BaseModel.Client.Timeout = requestOptions.Timeout;
}
HttpResponseMessage response = await BaseModel.Client.PostAsync(requestUri, content);
response.EnsureSuccessStatusCode();
return await Deserialize<CountTokensResponse>(response);
}
public async Task<GenerateMessageResponse> GenerateMessage(GenerateMessageRequest? request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
if (!_model.Equals("chat-bison-001".SanitizeModelName() ?? "", StringComparison.InvariantCultureIgnoreCase))
{
throw new NotSupportedException();
}
string requestUri = ParseUrl(Url, Method);
StringContent content = new StringContent(Serialize(request), Encoding.UTF8, "application/json");
HttpResponseMessage response = await BaseModel.Client.PostAsync(requestUri, content);
response.EnsureSuccessStatusCode();
return await Deserialize<GenerateMessageResponse>(response);
}
public async Task<GenerateMessageResponse> GenerateMessage(string prompt)
{
if (prompt == null)
{
throw new ArgumentNullException("prompt");
}
GenerateMessageRequest request = new GenerateMessageRequest(prompt);
return await GenerateMessage(request);
}
public async Task<CountTokensResponse> CountTokens(GenerateMessageRequest request, RequestOptions? requestOptions = null)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
string countMessageTokens = ML.GenAI.Method.CountMessageTokens;
string requestUri = ParseUrl(Url, countMessageTokens);
StringContent content = new StringContent(Serialize(request), Encoding.UTF8, "application/json");
if (requestOptions != null)
{
BaseModel.Client.Timeout = requestOptions.Timeout;
}
HttpResponseMessage response = await BaseModel.Client.PostAsync(requestUri, content);
response.EnsureSuccessStatusCode();
return await Deserialize<CountTokensResponse>(response);
}
public async Task<EmbedTextResponse> EmbedText(EmbedTextRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
if (!_model.Equals("embedding-gecko-001".SanitizeModelName() ?? "", StringComparison.InvariantCultureIgnoreCase))
{
throw new NotSupportedException();
}
string requestUri = ParseUrl(Url, Method);
StringContent content = new StringContent(Serialize(request), Encoding.UTF8, "application/json");
HttpResponseMessage response = await BaseModel.Client.PostAsync(requestUri, content);
response.EnsureSuccessStatusCode();
return await Deserialize<EmbedTextResponse>(response);
}
public async Task<EmbedTextResponse> EmbedText(string prompt)
{
if (prompt == null)
{
throw new ArgumentNullException("prompt");
}
if (!_model.Equals("embedding-gecko-001".SanitizeModelName() ?? "", StringComparison.InvariantCultureIgnoreCase))
{
throw new NotSupportedException();
}
EmbedTextRequest request = new EmbedTextRequest(prompt);
return await EmbedText(request);
}
public async Task<CountTokensResponse> CountTokens(EmbedTextRequest request, RequestOptions? requestOptions = null)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
string countMessageTokens = ML.GenAI.Method.CountMessageTokens;
string requestUri = ParseUrl(Url, countMessageTokens);
StringContent content = new StringContent(Serialize(request), Encoding.UTF8, "application/json");
if (requestOptions != null)
{
BaseModel.Client.Timeout = requestOptions.Timeout;
}
HttpResponseMessage response = await BaseModel.Client.PostAsync(requestUri, content);
response.EnsureSuccessStatusCode();
return await Deserialize<CountTokensResponse>(response);
}
public async Task<EmbedTextResponse> BatchEmbedText(BatchEmbedTextRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
if (!_model.Equals("embedding-gecko-001".SanitizeModelName() ?? "", StringComparison.InvariantCultureIgnoreCase))
{
throw new NotSupportedException();
}
string batchEmbedText = ML.GenAI.Method.BatchEmbedText;
string requestUri = ParseUrl(Url, batchEmbedText);
StringContent content = new StringContent(Serialize(request), Encoding.UTF8, "application/json");
return await Deserialize<EmbedTextResponse>(await BaseModel.Client.PostAsync(requestUri, content));
}
}
public class PredictRequest
{
public List<object> Instances { get; set; }
public List<object> Parameters { get; set; }
}
public class PredictResponse
{
public List<object> Predictions { get; set; }
}
public class PredictLongRunningRequest
{
public List<object> Instances { get; set; }
public List<object> Parameters { get; set; }
}
public class Operation
{
public string Name { get; set; }
public bool Done { get; set; }
public Status? Error { get; set; }
public object Metadata { get; set; }
public object Response { get; set; }
}
public class GenerateTextResponse
{
public string? Text => Candidates?.FirstOrDefault()?.Output;
public List<TextCompletion> Candidates { get; set; }
public List<ContentFilter>? Filters { get; set; }
public List<SafetyFeedback>? SafetyFeedback { get; set; }
public override string ToString()
{
return Text ?? string.Empty;
}
}
public sealed class SafetyFeedback
{
public SafetyRating Rating { get; set; }
public SafetySetting Setting { get; set; }
}
public class SafetyRating
{
public HarmCategory Category { get; set; }
public HarmProbability Probability { get; set; }
public bool? Blocked { get; set; }
public float? ProbabilityScore { get; set; }
public HarmSeverity? Severity { get; set; }
public float? SeverityScore { get; set; }
}
public sealed class TextCompletion
{
public string Output { get; set; }
public List<SafetyRating> SafetyRatings { get; set; }
public CitationMetadata CitationMetadata { get; set; }
}
public class GenerateTextRequest
{
public TextPrompt Prompt { get; set; }
public List<SafetySetting>? SafetySettings { get; set; }
public float? Temperature { get; set; }
public float? TopP { get; set; }
public int? TopK { get; set; }
public int? CandidateCount { get; set; }
public int? MaxOutputTokens { get; set; }
public List<string>? StopSequences { get; set; }
public GenerateTextRequest()
{
}
public GenerateTextRequest(string prompt)
: this()
{
Prompt = new TextPrompt
{
Text = prompt
};
}
}
public sealed class TextPrompt : AbstractText
{
}
public class GenerateMessageResponse
{
public string? Text => Candidates?.FirstOrDefault()?.Content;
public List<Message> Candidates { get; set; }
public List<Message>? Messages { get; set; }
public List<ContentFilter>? Filters { get; set; }
public override string ToString()
{
return Text ?? string.Empty;
}
}
public class ContentFilter
{
public BlockedReason BlockReason { get; set; }
public string Message { get; set; }
}
public class BatchEmbedTextRequest
{
public List<string>? Texts { get; set; }
public List<EmbedTextRequest>? Requests { get; set; }
}
public class EmbedTextRequest
{
public string? Text { get; set; }
public EmbedTextRequest()
{
}
public EmbedTextRequest(string text)
: this()
{
Text = text;
}
}
public class EmbedTextResponse
{
public Embedding? Embedding { get; set; }
public List<Embedding>? Embeddings { get; set; }
}
public class Embedding
{
public List<float> Value { get; set; }
}
public static class GenerativeAIExtensions
{
public static void GuardSupported(this GenerativeModel model, string? message = null)
{
if (message == null)
{
message = "Vertex AI or the model `" + model.Name + "` does not support this functionality.";
}
if (model.IsVertexAI)
{
throw new NotSupportedException(message);
}
}
public static void GuardInlineDataMimeType(string mimeType)
{
if (!new string[12]
{
"image/jpeg", "image/png", "image/heif", "image/heic", "image/webp", "audio/wav", "audio/mp3", "audio/mpeg", "audio/aiff", "audio/aac",
"audio/ogg", "audio/flac"
}.Contains(mimeType))
{
throw new NotSupportedException("The mime type `" + mimeType + "` is not supported by the API.");
}
}
public static void GuardMimeType(string mimeType)
{
if (!new string[33]
{
"image/jpeg", "image/png", "image/heif", "image/heic", "image/webp", "audio/wav", "audio/mp3", "audio/mpeg", "audio/aiff", "audio/aac",
"audio/ogg", "audio/flac", "video/mp4", "video/mpeg", "video/mov", "video/avi", "video/x-flv", "video/mpg", "video/webm", "video/wmv",
"video/3gpp", "application/pdf", "application/x-javascript", "text/javascript", "application/x-python", "text/x-python", "text/plain", "text/html", "text/css", "text/md",
"text/csv", "text/xml", "text/rtf"
}.Contains(mimeType))
{
throw new NotSupportedException("The mime type `" + mimeType + "` is not supported by the API.");
}
}
public static void GuardSupportedLanguage(this string language)
{
if (!new string[5] { "en", "de", "fr", "it", "es" }.Contains(language))
{
throw new NotSupportedException("The language `" + language + "` is not supported by the API.");
}
}
public static string SanitizeModelName(this string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
if (value.StartsWith("tuned", StringComparison.InvariantCultureIgnoreCase))
{
return value;
}
if (!value.StartsWith("model", StringComparison.InvariantCultureIgnoreCase))
{
return "models/" + value;
}
return value;
}
public static string SanitizeFileName(this string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
if (!value.StartsWith("file", StringComparison.InvariantCultureIgnoreCase))
{
return "files/" + value;
}
return value;
}
public static string SanitizeGeneratedFileName(this string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
if (!value.StartsWith("generatedFile", StringComparison.InvariantCultureIgnoreCase))
{
return "generatedFiles/" + value;
}
return value;
}
public static string SanitizeCachedContentName(this string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
if (!value.StartsWith("cachedContent", StringComparison.InvariantCultureIgnoreCase))
{
return "cachedContents/" + value;
}
return value;
}
public static string SanitizeTuningJobsName(this string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
if (!value.StartsWith("tuningJob", StringComparison.InvariantCultureIgnoreCase))
{
return "tuningJobs/" + value;
}
return value;
}
public static string SanitizeEndpointName(this string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
value.StartsWith("endpoint", StringComparison.InvariantCultureIgnoreCase);
return value;
}
public static string GetValue(this JsonElement element, string key)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
string text = "";
if (element.TryGetProperty(key, out var value))
{
text = value.GetString();
}
return text ?? "";
}
public static void ReadDotEnv(string dotEnvFile = ".env")
{
if (!File.Exists(dotEnvFile))
{
return;
}
string[] array = File.ReadAllLines(dotEnvFile);
for (int i = 0; i < array.Length; i++)
{
string[] array2 = array[i].Split(new char[1] { '=' }, StringSplitOptions.RemoveEmptyEntries);
if (array2.Length == 2)
{
Environment.SetEnvironmentVariable(array2[0], array2[1]);
}
}
}
public static string AddQueryString(this string requestUri, Dictionary<string, string?> queryStringParams)
{
bool flag = false;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append(requestUri);
foreach (KeyValuePair<string, string> queryStringParam in queryStringParams)
{
if (!string.IsNullOrEmpty(queryStringParam.Value))
{
stringBuilder.Append(flag ? '&' : '?');
StringBuilder stringBuilder2 = stringBuilder;
StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(1, 2, stringBuilder2);
handler.AppendFormatted(queryStringParam.Key);
handler.AppendLiteral("=");
handler.AppendFormatted(queryStringParam.Value);
stringBuilder2.Append(ref handler);
flag = true;
}
}
return stringBuilder.ToString();
}
public static void CheckResponse(this GenerateContentResponse response, bool stream = false)
{
PromptFeedback promptFeedback = response.PromptFeedback;
if (promptFeedback != null && promptFeedback.BlockReason != 0)
{
throw new BlockedPromptException(response.PromptFeedback);
}
if (stream)
{
return;
}
FinishReason? finishReason = response.Candidates[0].FinishReason;
bool flag;
if (finishReason.HasValue)
{
FinishReason valueOrDefault = finishReason.GetValueOrDefault();
if ((uint)(valueOrDefault - 3) <= 2u)
{
flag = true;
goto IL_0050;
}
}
flag = false;
goto IL_0050;
IL_0050:
if (flag)
{
throw new StopCandidateException(response.Candidates[0]);
}
}
internal static async Task<string> ReadImageFileBase64Async(string url)
{
using HttpClient client = new HttpClient();
using HttpResponseMessage response = await client.GetAsync(url);
return Convert.ToBase64String(await response.Content.ReadAsByteArrayAsync());
}
internal static async Task<byte[]> ReadImageFileAsync(string url)
{
using HttpClient client = new HttpClient();
using HttpResponseMessage response = await client.GetAsync(url);
return await response.Content.ReadAsByteArrayAsync();
}
internal static string GetMimeType(string uri)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
string text = Path.GetExtension(uri).ToLower();
if (text.StartsWith("."))
{
text = text.Substring(1);
}
return text switch
{
"323" => "text/h323",
"3g2" => "video/3gpp2",
"3gp" => "video/3gpp",
"3gp2" => "video/3gpp2",
"3gpp" => "video/3gpp",
"7z" => "application/x-7z-compressed",
"aa" => "audio/audible",
"aac" => "audio/aac",
"aaf" => "application/octet-stream",
"aax" => "audio/vnd.audible.aax",
"ac3" => "audio/ac3",
"aca" => "application/octet-stream",
"accda" => "application/msaccess.addin",
"accdb" => "application/msaccess",
"accdc" => "application/msaccess.cab",
"accde" => "application/msaccess",
"accdr" => "application/msaccess.runtime",
"accdt" => "application/msaccess",
"accdw" => "application/msaccess.webapplication",
"accft" => "application/msaccess.ftemplate",
"acx" => "application/internet-property-stream",
"addin" => "text/xml",
"ade" => "application/msaccess",
"adobebridge" => "application/x-bridge-url",
"adp" => "application/msaccess",
"adt" => "audio/vnd.dlna.adts",
"adts" => "audio/aac",
"afm" => "application/octet-stream",
"ai" => "application/postscript",
"aif" => "audio/x-aiff",
"aifc" => "audio/aiff",
"aiff" => "audio/aiff",
"air" => "application/vnd.adobe.air-application-installer-package+zip",
"amc" => "application/x-mpeg",
"application" => "application/x-ms-application",
"art" => "image/x-jg",
"asa" => "application/xml",
"asax" => "application/xml",
"ascx" => "application/xml",
"asd" => "application/octet-stream",
"asf" => "video/x-ms-asf",
"ashx" => "application/xml",
"asi" => "application/octet-stream",
"asm" => "text/plain",
"asmx" => "application/xml",
"aspx" => "application/xml",
"asr" => "video/x-ms-asf",
"asx" => "video/x-ms-asf",
"atom" => "application/atom+xml",
"au" => "audio/basic",
"avi" => "video/x-msvideo",
"axs" => "application/olescript",
"bas" => "text/plain",
"bcpio" => "application/x-bcpio",
"bin" => "application/octet-stream",
"bmp" => "image/bmp",
"c" => "text/plain",
"cab" => "application/octet-stream",
"caf" => "audio/x-caf",
"calx" => "application/vnd.ms-office.calx",
"cat" => "application/vnd.ms-pki.seccat",
"cc" => "text/plain",
"cd" => "text/plain",
"cdda" => "audio/aiff",
"cdf" => "application/x-cdf",
"cer" => "application/x-x509-ca-cert",
"chm" => "application/octet-stream",
"class" => "application/x-java-applet",
"clp" => "application/x-msclip",
"cmx" => "image/x-cmx",
"cnf" => "text/plain",
"cod" => "image/cis-cod",
"config" => "application/xml",
"contact" => "text/x-ms-contact",
"coverage" => "application/xml",
"cpio" => "application/x-cpio",
"cpp" => "text/plain",
"crd" => "application/x-mscardfile",
"crl" => "application/pkix-crl",
"crt" => "application/x-x509-ca-cert",
"cs" => "text/plain",
"csdproj" => "text/plain",
"csh" => "application/x-csh",
"csproj" => "text/plain",
"css" => "text/css",
"csv" => "text/csv",
"cur" => "application/octet-stream",
"cxx" => "text/plain",
"dat" => "application/octet-stream",
"datasource" => "application/xml",
"dbproj" => "text/plain",
"dcr" => "application/x-director",
"def" => "text/plain",
"deploy" => "application/octet-stream",
"der" => "application/x-x509-ca-cert",
"dgml" => "application/xml",
"dib" => "image/bmp",
"dif" => "video/x-dv",
"dir" => "application/x-director",
"disco" => "text/xml",
"dll" => "application/x-msdownload",
"dll.config" => "text/xml",
"dlm" => "text/dlm",
"doc" => "application/msword",
"docm" => "application/vnd.ms-word.document.macroenabled.12",
"docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"dot" => "application/msword",
"dotm" => "application/vnd.ms-word.template.macroenabled.12",
"dotx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.template",
"dsp" => "application/octet-stream",
"dsw" => "text/plain",
"dtd" => "text/xml",
"dtsconfig" => "text/xml",
"dv" => "video/x-dv",
"dvi" => "application/x-dvi",
"dwf" => "drawing/x-dwf",
"dwp" => "application/octet-stream",
"dxr" => "application/x-director",
"eml" => "message/rfc822",
"emz" => "application/octet-stream",
"eot" => "application/octet-stream",
"eps" => "application/postscript",
"etl" => "application/etl",
"etx" => "text/x-setext",
"evy" => "application/envoy",
"exe" => "application/octet-stream",
"exe.config" => "text/xml",
"fdf" => "application/vnd.fdf",
"fif" => "application/fractals",
"filters" => "application/xml",
"fla" => "application/octet-stream",
"flr" => "x-world/x-vrml",
"flv" => "video/x-flv",
"fsscript" => "application/fsharp-script",
"fsx" => "application/fsharp-script",
"generictest" => "application/xml",
"gif" => "image/gif",
"group" => "text/x-ms-group",
"gsm" => "audio/x-gsm",
"gtar" => "application/x-gtar",
"gz" => "application/x-gzip",
"h" => "text/plain",
"hdf" => "application/x-hdf",
"hdml" => "text/x-hdml",
"hhc" => "application/x-oleobject",
"hhk" => "application/octet-stream",
"hhp" => "application/octet-stream",
"hlp" => "application/winhlp",
"hpp" => "text/plain",
"hqx" => "application/mac-binhex40",
"hta" => "application/hta",
"htc" => "text/x-component",
"htm" => "text/html",
"html" => "text/html",
"htt" => "text/webviewhtml",
"hxa" => "application/xml",
"hxc" => "application/xml",
"hxd" => "application/octet-stream",
"hxe" => "application/xml",
"hxf" => "application/xml",
"hxh" => "application/octet-stream",
"hxi" => "application/octet-stream",
"hxk" => "application/xml",
"hxq" => "application/octet-stream",
"hxr" => "application/octet-stream",
"hxs" => "application/octet-stream",
"hxt" => "text/html",
"hxv" => "application/xml",
"hxw" => "application/octet-stream",
"hxx" => "text/plain",
"i" => "text/plain",
"ico" => "image/x-icon",
"ics" => "application/octet-stream",
"idl" => "text/plain",
"ief" => "image/ief",
"iii" => "application/x-iphone",
"inc" => "text/plain",
"inf" => "application/octet-stream",
"inl" => "text/plain",
"ins" => "application/x-internet-signup",
"ipa" => "application/x-itunes-ipa",
"ipg" => "application/x-itunes-ipg",
"ipproj" => "text/plain",
"ipsw" => "application/x-itunes-ipsw",
"iqy" => "text/x-ms-iqy",
"isp" => "application/x-internet-signup",
"ite" => "application/x-itunes-ite",
"itlp" => "application/x-itunes-itlp",
"itms" => "application/x-itunes-itms",
"itpc" => "application/x-itunes-itpc",
"ivf" => "video/x-ivf",
"jar" => "application/java-archive",
"java" => "application/octet-stream",
"jck" => "application/liquidmotion",
"jcz" => "application/liquidmotion",
"jfif" => "image/pjpeg",
"jnlp" => "application/x-java-jnlp-file",
"jpb" => "application/octet-stream",
"jpe" => "image/jpeg",
"jpeg" => "image/jpeg",
"jpg" => "image/jpeg",
"js" => "application/x-javascript",
"jsx" => "text/jscript",
"jsxbin" => "text/plain",
"latex" => "application/x-latex",
"library-ms" => "application/windows-library+xml",
"lit" => "application/x-ms-reader",
"loadtest" => "application/xml",
"lpk" => "application/octet-stream",
"lsf" => "video/x-la-asf",
"lst" => "text/plain",
"lsx" => "video/x-la-asf",
"lzh" => "application/octet-stream",
"m13" => "application/x-msmediaview",
"m14" => "application/x-msmediaview",
"m1v" => "video/mpeg",
"m2t" => "video/vnd.dlna.mpeg-tts",
"m2ts" => "video/vnd.dlna.mpeg-tts",
"m2v" => "video/mpeg",
"m3u" => "audio/x-mpegurl",
"m3u8" => "audio/x-mpegurl",
"m4a" => "audio/m4a",
"m4b" => "audio/m4b",
"m4p" => "audio/m4p",
"m4r" => "audio/x-m4r",
"m4v" => "video/x-m4v",
"mac" => "image/x-macpaint",
"mak" => "text/plain",
"man" => "application/x-troff-man",
"manifest" => "application/x-ms-manifest",
"map" => "text/plain",
"master" => "application/xml",
"mda" => "application/msaccess",
"mdb" => "application/x-msaccess",
"mde" => "application/msaccess",
"mdp" => "application/octet-stream",
"me" => "application/x-troff-me",
"mfp" => "application/x-shockwave-flash",
"mht" => "message/rfc822",
"mhtml" => "message/rfc822",
"mid" => "audio/mid",
"midi" => "audio/mid",
"mix" => "application/octet-stream",
"mk" => "text/plain",
"mmf" => "application/x-smaf",
"mno" => "text/xml",
"mny" => "application/x-msmoney",
"mod" => "video/mpeg",
"mov" => "video/quicktime",
"movie" => "video/x-sgi-movie",
"mp2" => "video/mpeg",
"mp2v" => "video/mpeg",
"mp3" => "audio/mpeg",
"mp4" => "video/mp4",
"mp4v" => "video/mp4",
"mpa" => "video/mpeg",
"mpe" => "video/mpeg",
"mpeg" => "video/mpeg",
"mpf" => "application/vnd.ms-mediapackage",
"mpg" => "video/mpeg",
"mpp" => "application/vnd.ms-project",
"mpv2" => "video/mpeg",
"mqv" => "video/quicktime",
"ms" => "application/x-troff-ms",
"msi" => "application/octet-stream",
"mso" => "application/octet-stream",
"mts" => "video/vnd.dlna.mpeg-tts",
"mtx" => "application/xml",
"mvb" => "application/x-msmediaview",
"mvc" => "application/x-miva-compiled",
"mxp" => "application/x-mmxp",
"nc" => "application/x-netcdf",
"nsc" => "video/x-ms-asf",
"nws" => "message/rfc822",
"ocx" => "application/octet-stream",
"oda" => "application/oda",
"odc" => "text/x-ms-odc",
"odh" => "text/plain",
"odl" => "text/plain",
"odp" => "application/vnd.oasis.opendocument.presentation",
"ods" => "application/oleobject",
"odt" => "application/vnd.oasis.opendocument.text",
"one" => "application/onenote",
"onea" => "application/onenote",
"onepkg" => "application/onenote",
"onetmp" => "application/onenote",
"onetoc" => "application/onenote",
"onetoc2" => "application/onenote",
"orderedtest" => "application/xml",
"osdx" => "application/opensearchdescription+xml",
"p10" => "application/pkcs10",
"p12" => "application/x-pkcs12",
"p7b" => "application/x-pkcs7-certificates",
"p7c" => "application/pkcs7-mime",
"p7m" => "application/pkcs7-mime",
"p7r" => "application/x-pkcs7-certreqresp",
"p7s" => "application/pkcs7-signature",
"pbm" => "image/x-portable-bitmap",
"pcast" => "application/x-podcast",
"pct" => "image/pict",
"pcx" => "application/octet-stream",
"pcz" => "application/octet-stream",
"pdf" => "application/pdf",
"pfb" => "application/octet-stream",
"pfm" => "application/octet-stream",
"pfx" => "application/x-pkcs12",
"pgm" => "image/x-portable-graymap",
"pic" => "image/pict",
"pict" => "image/pict",
"pkgdef" => "text/plain",
"pkgundef" => "text/plain",
"pko" => "application/vnd.ms-pki.pko",
"pls" => "audio/scpls",
"pma" => "application/x-perfmon",
"pmc" => "application/x-perfmon",
"pml" => "application/x-perfmon",
"pmr" => "application/x-perfmon",
"pmw" => "application/x-perfmon",
"png" => "image/png",
"pnm" => "image/x-portable-anymap",
"pnt" => "image/x-macpaint",
"pntg" => "image/x-macpaint",
"pnz" => "image/png",
"pot" => "application/vnd.ms-powerpoint",
"potm" => "application/vnd.ms-powerpoint.template.macroenabled.12",
"potx" => "application/vnd.openxmlformats-officedocument.presentationml.template",
"ppa" => "application/vnd.ms-powerpoint",
"ppam" => "application/vnd.ms-powerpoint.addin.macroenabled.12",
"ppm" => "image/x-portable-pixmap",
"pps" => "application/vnd.ms-powerpoint",
"ppsm" => "application/vnd.ms-powerpoint.slideshow.macroenabled.12",
"ppsx" => "application/vnd.openxmlformats-officedocument.presentationml.slideshow",
"ppt" => "application/vnd.ms-powerpoint",
"pptm" => "application/vnd.ms-powerpoint.presentation.macroenabled.12",
"pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
"prf" => "application/pics-rules",
"prm" => "application/octet-stream",
"prx" => "application/octet-stream",
"ps" => "application/postscript",
"psc1" => "application/powershell",
"psd" => "application/octet-stream",
"psess" => "application/xml",
"psm" => "application/octet-stream",
"psp" => "application/octet-stream",
"pub" => "application/x-mspublisher",
"pwz" => "application/vnd.ms-powerpoint",
"qht" => "text/x-html-insertion",
"qhtm" => "text/x-html-insertion",
"qt" => "video/quicktime",
"qti" => "image/x-quicktime",
"qtif" => "image/x-quicktime",
"qtl" => "application/x-quicktimeplayer",
"qxd" => "application/octet-stream",
"ra" => "audio/x-pn-realaudio",
"ram" => "audio/x-pn-realaudio",
"rar" => "application/octet-stream",
"ras" => "image/x-cmu-raster",
"rat" => "application/rat-file",
"rc" => "text/plain",
"rc2" => "text/plain",
"rct" => "text/plain",
"rdlc" => "application/xml",
"resx" => "application/xml",
"rf" => "image/vnd.rn-realflash",
"rgb" => "image/x-rgb",
"rgs" => "text/plain",
"rm" => "application/vnd.rn-realmedia",
"rmi" => "audio/mid",
"rmp" => "application/vnd.rn-rn_music_package",
"roff" => "application/x-troff",
"rpm" => "audio/x-pn-realaudio-plugin",
"rqy" => "text/x-ms-rqy",
"rtf" => "application/rtf",
"rtx" => "text/richtext",
"ruleset" => "application/xml",
"s" => "text/plain",
"safariextz" => "application/x-safari-safariextz",
"scd" => "application/x-msschedule",
"sct" => "text/scriptlet",
"sd2" => "audio/x-sd2",
"sdp" => "application/sdp",
"sea" => "application/octet-stream",
"searchconnector-ms" => "application/windows-search-connector+xml",
"setpay" => "application/set-payment-initiation",
"setreg" => "application/set-registration-initiation",
"settings" => "application/xml",
"sgimb" => "application/x-sgimb",
"sgml" => "text/sgml",
"sh" => "application/x-sh",
"shar" => "application/x-shar",
"shtml" => "text/html",
"sit" => "application/x-stuffit",
"sitemap" => "application/xml",
"skin" => "application/xml",
"sldm" => "application/vnd.ms-powerpoint.slide.macroenabled.12",
"sldx" => "application/vnd.openxmlformats-officedocument.presentationml.slide",
"slk" => "application/vnd.ms-excel",
"sln" => "text/plain",
"slupkg-ms" => "application/x-ms-license",
"smd" => "audio/x-smd",
"smi" => "application/octet-stream",
"smx" => "audio/x-smd",
"smz" => "audio/x-smd",
"snd" => "audio/basic",
"snippet" => "application/xml",
"snp" => "application/octet-stream",
"sol" => "text/plain",
"sor" => "text/plain",
"spc" => "application/x-pkcs7-certificates",
"spl" => "application/futuresplash",
"src" => "application/x-wais-source",
"srf" => "text/plain",
"ssisdeploymentmanifest" => "text/xml",
"ssm" => "application/streamingmedia",
"sst" => "application/vnd.ms-pki.certstore",
"stl" => "application/vnd.ms-pki.stl",
"sv4cpio" => "application/x-sv4cpio",
"sv4crc" => "application/x-sv4crc",
"svc" => "application/xml",
"swf" => "application/x-shockwave-flash",
"t" => "application/x-troff",
"tar" => "application/x-tar",
"tcl" => "application/x-tcl",
"testrunconfig" => "application/xml",
"testsettings" => "application/xml",
"tex" => "application/x-tex",
"texi" => "application/x-texinfo",
"texinfo" => "application/x-texinfo",
"tgz" => "application/x-compressed",
"thmx" => "application/vnd.ms-officetheme",
"thn" => "application/octet-stream",
"tif" => "image/tiff",
"tiff" => "image/tiff",
"tlh" => "text/plain",
"tli" => "text/plain",
"toc" => "application/octet-stream",
"tr" => "application/x-troff",
"trm" => "application/x-msterminal",
"trx" => "application/xml",
"ts" => "video/vnd.dlna.mpeg-tts",
"tsv" => "text/tab-separated-values",
"ttf" => "application/octet-stream",
"tts" => "video/vnd.dlna.mpeg-tts",
"txt" => "text/plain",
"u32" => "application/octet-stream",
"uls" => "text/iuls",
"user" => "text/plain",
"ustar" => "application/x-ustar",
"vb" => "text/plain",
"vbdproj" => "text/plain",
"vbk" => "video/mpeg",
"vbproj" => "text/plain",
"vbs" => "text/vbscript",
"vcf" => "text/x-vcard",
"vcproj" => "application/xml",
"vcs" => "text/plain",
"vcxproj" => "application/xml",
"vddproj" => "text/plain",
"vdp" => "text/plain",
"vdproj" => "text/plain",
"vdx" => "application/vnd.ms-visio.viewer",
"vml" => "text/xml",
"vscontent" => "application/xml",
"vsct" => "text/xml",
"vsd" => "application/vnd.visio",
"vsi" => "application/ms-vsi",
"vsix" => "application/vsix",
"vsixlangpack" => "text/xml",
"vsixmanifest" => "text/xml",
"vsmdi" => "application/xml",
"vspscc" => "text/plain",
"vss" => "application/vnd.visio",
"vsscc" => "text/plain",
"vssettings" => "text/xml",
"vssscc" => "text/plain",
"vst" => "application/vnd.visio",
"vstemplate" => "text/xml",
"vsto" => "application/x-ms-vsto",
"vsw" => "application/vnd.visio",
"vsx" => "application/vnd.visio",
"vtx" => "application/vnd.visio",
"wav" => "audio/wav",
"wave" => "audio/wav",
"wax" => "audio/x-ms-wax",
"wbk" => "application/msword",
"wbmp" => "image/vnd.wap.wbmp",
"wcm" => "application/vnd.ms-works",
"wdb" => "application/vnd.ms-works",
"wdp" => "image/vnd.ms-photo",
"webarchive" => "application/x-safari-webarchive",
"webtest" => "application/xml",
"wiq" => "application/xml",
"wiz" => "application/msword",
"wks" => "application/vnd.ms-works",
"wlmp" => "application/wlmoviemaker",
"wlpginstall" => "application/x-wlpg-detect",
"wlpginstall3" => "application/x-wlpg3-detect",
"wm" => "video/x-ms-wm",
"wma" => "audio/x-ms-wma",
"wmd" => "application/x-ms-wmd",
"wmf" => "application/x-msmetafile",
"wml" => "text/vnd.wap.wml",
"wmlc" => "application/vnd.wap.wmlc",
"wmls" => "text/vnd.wap.wmlscript",
"wmlsc" => "application/vnd.wap.wmlscriptc",
"wmp" => "video/x-ms-wmp",
"wmv" => "video/x-ms-wmv",
"wmx" => "video/x-ms-wmx",
"wmz" => "application/x-ms-wmz",
"wpl" => "application/vnd.ms-wpl",
"wps" => "application/vnd.ms-works",
"wri" => "application/x-mswrite",
"wrl" => "x-world/x-vrml",
"wrz" => "x-world/x-vrml",
"wsc" => "text/scriptlet",
"wsdl" => "text/xml",
"wvx" => "video/x-ms-wvx",
"x" => "application/directx",
"xaf" => "x-world/x-vrml",
"xaml" => "application/xaml+xml",
"xap" => "application/x-silverlight-app",
"xbap" => "application/x-ms-xbap",
"xbm" => "image/x-xbitmap",
"xdr" => "text/plain",
"xht" => "application/xhtml+xml",
"xhtml" => "application/xhtml+xml",
"xla" => "application/vnd.ms-excel",
"xlam" => "application/vnd.ms-excel.addin.macroenabled.12",
"xlc" => "application/vnd.ms-excel",
"xld" => "application/vnd.ms-excel",
"xlk" => "application/vnd.ms-excel",
"xll" => "application/vnd.ms-excel",
"xlm" => "application/vnd.ms-excel",
"xls" => "application/vnd.ms-excel",
"xlsb" => "application/vnd.ms-excel.sheet.binary.macroenabled.12",
"xlsm" => "application/vnd.ms-excel.sheet.macroenabled.12",
"xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"xlt" => "application/vnd.ms-excel",
"xltm" => "application/vnd.ms-excel.template.macroenabled.12",
"xltx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.template",
"xlw" => "application/vnd.ms-excel",
"xml" => "text/xml",
"xmta" => "application/xml",
"xof" => "x-world/x-vrml",
"xoml" => "text/plain",
"xpm" => "image/x-xpixmap",
"xps" => "application/vnd.ms-xpsdocument",
"xrm-ms" => "text/xml",
"xsc" => "application/xml",
"xsd" => "text/xml",
"xsf" => "text/xml",
"xsl" => "text/xml",
"xslt" => "text/xml",
"xsn" => "application/octet-stream",
"xss" => "application/xml",
"xtp" => "application/octet-stream",
"xwd" => "image/x-xwindowdump",
"z" => "application/x-compress",
"zip" => "application/x-zip-compressed",
_ => "application/octet-stream",
};
}
internal static async Task<HttpResponseMessage> EnsureSuccessAsync(this HttpResponseMessage response, string? errorMessage = null, bool includeResponseContent = true)
{
if (response.IsSuccessStatusCode)
{
return response;
}
errorMessage = ((!string.IsNullOrEmpty(errorMessage)) ? errorMessage : "Request failed");
string text;
if (includeResponseContent)
{
string newLine = Environment.NewLine;
text = newLine + await response.Content.ReadAsStringAsync();
}
else
{
text = string.Empty;
}
string value = text;
throw new HttpRequestException($"{errorMessage}{Environment.NewLine}{"Request failed with Status Code: "}{response.StatusCode}{value.Truncate()}");
}
internal static string Truncate(this string value, int maxLength = 4096, string suffix = "…")
{
if (string.IsNullOrWhiteSpace(value))
{
return value;
}
if (string.IsNullOrEmpty(suffix))
{
throw new ArgumentException("suffix");
}
if (suffix.Length > maxLength)
{
throw new ArgumentOutOfRangeException("suffix", $"Suffix '{suffix}' (length {suffix.Length} cannot be larger than maximal length {maxLength}.");
}
if (maxLength - suffix.Length >= 0 && maxLength - suffix.Length <= value.Length)
{
value = ((value.Length >= maxLength) ? (value.Substring(0, maxLength - suffix.Length) + suffix) : value);
}
return value;
}
}
public class BlockedPromptException : Exception
{
public BlockedPromptException()
{
}
public BlockedPromptException(string? message)
: base(message)
{
}
public BlockedPromptException(string? message, Exception? innerException)
: base(message, innerException)
{
}
public BlockedPromptException(PromptFeedback promptFeedback)
: base(promptFeedback.BlockReasonMessage)
{
}
}
public class ChatSession
{
private readonly GenerativeModel _model;
private readonly GenerationConfig? _generationConfig;
private readonly List<SafetySetting>? _safetySettings;
private readonly List<Tool>? _tools;
private readonly bool _enableAutomaticFunctionCalling;
private List<ContentResponse> _history;
private ContentResponse? _lastSent;
private ContentResponse? _lastReceived;
public List<ContentResponse> History
{
get
{
return _history;
}
set
{
_history = value;
_lastSent = null;
_lastReceived = null;
}
}
public ContentResponse? Last => _lastReceived;
public ChatSession(GenerativeModel model, List<ContentResponse>? history = null, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null, List<Tool>? tools = null, bool enableAutomaticFunctionCalling = false)
{
_model = model;
History = history ?? new List<ContentResponse>();
_generationConfig = generationConfig;
_safetySettings = safetySettings;
_tools = tools;
_enableAutomaticFunctionCalling = enableAutomaticFunctionCalling;
}
public async Task<GenerateContentResponse> SendMessage(object content, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null, List<Tool>? tools = null, ToolConfig? toolConfig = null)
{
if (content == null)
{
throw new ArgumentNullException("content");
}
if (!(content is string) && !(content is List<Part>))
{
throw new ArgumentException(content.ToString(), "content");
}
if (generationConfig == null)
{
generationConfig = _generationConfig;
}
GenerationConfig? generationConfig2 = generationConfig;
if (generationConfig2 != null && generationConfig2.CandidateCount > 1)
{
throw new ValueErrorException("Can't chat with `CandidateCount > 1`");
}
string role = "user";
List<Part> list = new List<Part>();
if (content is string text)
{
list.Add(new Part
{
Text = text
});
}
if (content is List<Part> list2)
{
list = list2;
}
_lastSent = new ContentResponse
{
Role = role,
Parts = list
};
History.Add(_lastSent);
GenerateContentRequest request = new GenerateContentRequest
{
Contents = History.Select((ContentResponse x) => new Content
{
Role = x.Role,
PartTypes = x.Parts
}).ToList(),
GenerationConfig = (generationConfig ?? _generationConfig),
SafetySettings = (safetySettings ?? _safetySettings),
Tools = (tools ?? _tools),
ToolConfig = toolConfig
};
GenerateContentResponse generateContentResponse = await _model.GenerateContent(request);
generateContentResponse.CheckResponse();
if (_enableAutomaticFunctionCalling)
{
HandleAutomaticFunctionCalling(generateContentResponse, History, generationConfig ?? _generationConfig, safetySettings ?? _safetySettings, _tools);
}
_lastReceived = new ContentResponse
{
Role = "model",
Text = (generateContentResponse.Text ?? string.Empty)
};
History.Add(_lastReceived);
return generateContentResponse;
}
public async IAsyncEnumerable<GenerateContentResponse> SendMessageStream(object content, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null, List<Tool>? tools = null, ToolConfig? toolConfig = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
{
if (content == null)
{
throw new ArgumentNullException("content");
}
if (!(content is string) && !(content is List<Part>))
{
throw new ArgumentException(content.ToString(), "content");
}
if (generationConfig == null)
{
generationConfig = _generationConfig;
}
GenerationConfig? generationConfig2 = generationConfig;
if (generationConfig2 != null && generationConfig2.CandidateCount > 1)
{
throw new ValueErrorException("Can't chat with `CandidateCount > 1`");
}
string role = "user";
List<Part> list = new List<Part>();
if (content is string text)
{
role = "user";
list.Add(new Part
{
Text = text
});
}
if (content is List<Part> list2)
{
role = "function";
list = list2;
}
_lastSent = new ContentResponse
{
Role = role,
Parts = list
};
History.Add(_lastSent);
GenerateContentRequest request = new GenerateContentRequest
{
Contents = History.Select((ContentResponse x) => new Content
{
Role = x.Role,
PartTypes = x.Parts
}).ToList(),
GenerationConfig = (generationConfig ?? _generationConfig),
SafetySettings = (safetySettings ?? _safetySettings),
Tools = (tools ?? _tools),
ToolConfig = toolConfig
};
StringBuilder fullText = new StringBuilder();
IAsyncEnumerable<GenerateContentResponse> asyncEnumerable = _model.GenerateContentStream(request, null, cancellationToken);
await foreach (GenerateContentResponse item in asyncEnumerable)
{
item.CheckResponse(stream: true);
if (cancellationToken.IsCancellationRequested)
{
break;
}
fullText.Append(item.Text);
yield return item;
}
_lastReceived = new ContentResponse
{
Role = "model",
Text = fullText.ToString()
};
History.Add(_lastReceived);
}
public (ContentResponse? Sent, ContentResponse? Received) Rewind()
{
int index = History.Count - 2;
(ContentResponse, ContentResponse) result;
if (_lastReceived == null)
{
List<ContentResponse> range = History.GetRange(index, 2);
result = (range.FirstOrDefault(), range.LastOrDefault());
}
else
{
result = (_lastSent, _lastReceived);
_lastSent = null;
_lastReceived = null;
}
History.RemoveRange(index, 2);
return result;
}
private (List<ContentResponse> history, ContentResponse content, GenerateContentResponse response) HandleAutomaticFunctionCalling(GenerateContentResponse response, List<ContentResponse> history, GenerationConfig? generationConfig, List<SafetySetting>? safetySettings, List<Tool>? tools)
{
throw new NotImplementedException();
}
private List<FunctionCall> GetFunctionCalls(GenerateContentResponse response)
{
if (response.Candidates.Count != 1)
{
throw new ValueErrorException($"Automatic function calling only works with 1 candidate, got {response.Candidates.Count}");
}
return (from x in response.Candidates[0].Content.Parts
where x.FunctionCall != null
select x.FunctionCall).ToList();
}
}
public class ValueErrorException : Exception
{
public ValueErrorException()
{
}
public ValueErrorException(string? message)
: base(message)
{
}
public ValueErrorException(string? message, Exception? innerException)
: base(message, innerException)
{
}
}
public sealed class ContentResponse
{
public List<Part> Parts { get; set; }
public string Role { get; set; }
[JsonIgnore]
public string Text
{
get
{
if (Parts.Count > 0)
{
return Parts[0].Text;
}
return string.Empty;
}
set
{
if (Parts.Count == 0)
{
Parts.Add(new Part
{
Text = value
});
}
else
{
Parts[0].Text = value;
}
}
}
internal ContentResponse()
{
Parts = new List<Part>();
}
public ContentResponse(string text, string role = "user")
: this()
{
Parts.Add(new Part
{
Text = text
});
Role = role;
}
}
public sealed class Content
{
private List<Part>? _partTypes;
[JsonIgnore]
public List<IPart>? Parts { get; set; }
[JsonPropertyOrder(-1)]
public string? Role { get; set; }
[JsonPropertyName("parts")]
public List<Part>? PartTypes
{
get
{
SynchronizeParts();
return _partTypes;
}
set
{
_partTypes = value;
}
}
internal Content()
{
Parts = new List<IPart>();
}
public Content(string text)
: this()
{
Parts?.Add(new TextData
{
Text = text
});
}
public Content(FileData file)
: this()
{
Role = "user";
Parts?.Add(new FileData
{
FileUri = file.FileUri,
MimeType = file.MimeType
});
}
private void SynchronizeParts()
{
if (Parts == null)
{
return;
}
List<IPart>? parts = Parts;
if (parts != null && parts.Count == 0)
{
return;
}
_partTypes = new List<Part>();
foreach (IPart part in Parts)
{
if (part is TextData textData)
{
_partTypes.Add(new Part
{
TextData = textData
});
}
if (part is InlineData inlineData)
{
_partTypes.Add(new Part
{
InlineData = inlineData
});
}
if (part is FileData fileData)
{
_partTypes.Add(new Part
{
FileData = fileData
});
}
if (part is FunctionResponse functionResponse)
{
_partTypes.Add(new Part
{
FunctionResponse = functionResponse
});
}
if (part is FunctionCall functionCall)
{
_partTypes.Add(new Part
{
FunctionCall = functionCall
});
}
if (part is VideoMetadata videoMetadata)
{
_partTypes.Add(new Part
{
VideoMetadata = videoMetadata
});
}
if (part is ExecutableCode executableCode)
{
_partTypes.Add(new Part
{
ExecutableCode = executableCode
});
}
if (part is CodeExecutionResult codeExecutionResult)
{
_partTypes.Add(new Part
{
CodeExecutionResult = codeExecutionResult
});
}
}
}
}
public class Part
{
public string Text
{
get
{
string text = TextData?.Text;
if (string.IsNullOrEmpty(text))
{
text = ExecutableCode?.Code;
}
if (string.IsNullOrEmpty(text))
{
text = CodeExecutionResult?.Output;
}
return text;
}
set
{
TextData = new TextData
{
Text = value
};
}
}
internal TextData TextData { get; set; }
public InlineData InlineData { get; set; }
public FileData FileData { get; set; }
public FunctionResponse FunctionResponse { get; set; }
public FunctionCall FunctionCall { get; set; }
public VideoMetadata VideoMetadata { get; set; }
public ExecutableCode ExecutableCode { get; set; }
public CodeExecutionResult CodeExecutionResult { get; set; }
public Part()
{
}
public Part(string text)
{
Text = text;
}
public Part(FileData fileData)
: this()
{
FileData = fileData;
}
public FileData FromUri(string uri, string mimetype)
{
return new FileData
{
FileUri = uri,
MimeType = mimetype
};
}
}
public class CodeExecutionResult : IPart
{
public Outcome Outcome { get; set; }
public string? Output { get; set; }
}
public class FunctionResponse : IPart
{
public string Name { get; set; } = string.Empty;
public dynamic? Response { get; set; }
}
public class ExecutableCode : IPart
{
public Language Language { get; set; }
public string Code { get; set; }
}
public class EmbedContentRequest
{
public string? Model { get; set; }
public ContentResponse? Content { get; set; }
public TaskType? TaskType { get; set; }
public string? Title { get; set; }
public int? OutputDimensionality { get; set; }
public EmbedContentRequest()
{
}
public EmbedContentRequest(string prompt)
{
Content = new ContentResponse
{
Text = prompt,
Role = "user"
};
}
public EmbedContentRequest(List<string> prompts)
{
Content = new ContentResponse();
foreach (string prompt in prompts)
{
Content.Parts.Add(new Part
{
Text = prompt
});
}
}
}
public static class Method
{
public static string BatchEmbedContents = "batchEmbedContents";
public static string CountTokens = "countTokens";
public static string EmbedContent = "embedContent";
public static string GenerateAnswer = "generateAnswer";
public static string GenerateContent = "generateContent";
public static string Get = "get";
public static string List = "list";
public static string StreamGenerateContent = "streamGenerateContent";
public static string Predict = "predict";
public static string PredictLongRunning = "predictLongRunning";
public static string Create = "create";
public static string CreateTunedModel = "createTunedModel";
public static string CreateTunedTextModel = "createTunedTextModel";
public static string Delete = "delete";
public static string GenerateText = "generateText";
public static string Patch = "patch";
public static string TransferOwnership = "transferOwnership";
public static string TunedModels = "tunedModels";
public static string TuningJobs = "tuningJobs";
public static string CachedContents = "cachedContents";
public static string BatchEmbedText = "batchEmbedText";
public static string CountMessageTokens = "countMessageTokens";
public static string CountTextTokens = "countTextTokens";
public static string EmbedText = "embedText";
public static string GenerateMessage = "ge0nerateMessage";
}
public class ListTunedModelResponse
{
public List<ModelResponse> TunedModels { get; set; }
}
internal class ListModelsResponse
{
public List<ModelResponse>? Models { get; set; }
public string? NextPageToken { get; set; }
}
public sealed class TextData : AbstractText, IPart
{
}
public abstract class AbstractText
{
public string Text { get; set; }
}
public class GenerationConfig
{
public float? Temperature { get; set; }
public float? TopP { get; set; }
public int? TopK { get; set; }
public int? CandidateCount { get; set; }
public int? MaxOutputTokens { get; set; }
public List<string>? StopSequences { get; set; }
public string? ResponseMimeType { get; set; }
public string? ResponseSchema { get; set; }
public float? PresencePenalty { get; set; }
public float? FrequencyPenalty { get; set; }
public bool? ResponseLogprobs { get; set; }
public int? Logprobs { get; set; }
}
public class SafetySetting
{
public HarmCategory Category { get; set; }
public HarmBlockThreshold Threshold { get; set; }
}
public class Tool
{
public List<FunctionDeclaration>? FunctionDeclarations { get; set; }
public CodeExecution? CodeExecution { get; set; }
public Retrieval? Retrieval { get; set; }
public GoogleSearchRetrieval? GoogleSearchRetrieval { get; set; }
}
public class Retrieval
{
public bool? DisableAttribution { get; set; }
public VertexAISearch VertexAiSearch { get; set; }
}
public class VertexAISearch
{
public string Datastore { get; set; }
}
public class CodeExecution
{
}
public class FunctionDeclaration
{
public string Name { get; set; } = string.Empty;
public string? Description { get; set; } = string.Empty;
public Schema? Parameters { get; set; }
}
public class Schema
{
public ParameterType? Type { get; set; }
public string Format { get; set; } = "";
public string Description { get; set; } = "";
public bool? Nullable { get; set; }
public Schema? Items { get; set; }
public List<string>? Enum { get; set; }
public dynamic? Properties { get; set; }
public List<string>? Required { get; set; }
}
public sealed class ToolConfig
{
public FunctionCallingConfig FunctionCallingConfig { get; set; }
}
public sealed class FunctionCallingConfig
{
public FunctionCallingMode Mode { get; set; }
public List<string>? AllowedFunctionNames { get; set; }
}
public class CachedContent
{
private string _model;
private string _name;
public string Model
{
get
{
return _model;
}
set
{
_model = value.SanitizeModelName() ?? throw new InvalidOperationException();
}
}
public string Name
{
get
{
return _name;
}
set
{
_name = value.SanitizeCachedContentName() ?? throw new InvalidOperationException();
}
}
public string? DisplayName { get; set; }
[JsonIgnore]
public string Expiration
{
get
{
string text = ExpireTime?.ToString("o");
if (text == null)
{
text = TtlString;
}
return text;
}
}
[JsonIgnore]
public TimeSpan Ttl { get; set; }
[JsonPropertyName("ttl")]
public string TtlString
{
get
{
return $"{Ttl.TotalSeconds}s";
}
set
{
if (TimeSpan.TryParse(value, out var result))
{
Ttl = result;
}
}
}
public DateTime? CreateTime { get; set; }
public DateTime? UpdateTime { get; set; }
public DateTime? ExpireTime { get; set; }
public List<Content>? Contents { get; set; }
public Content? SystemInstruction { get; set; }
public List<Tool>? Tools { get; set; }
public ToolConfig? ToolConfig { get; set; }
public CachedContentUsageMetadata? UsageMetadata { get; set; }
}
public class CachedContentUsageMetadata
{
public int TotalTokenCount { get; set; }
}
public class TuningJob
{
public string Name { get; set; } = string.Empty;
public string TunedModelDisplayName { get; set; } = string.Empty;
public string BaseModel { get; set; } = string.Empty;
public DateTime? CreateTime { get; set; }
public DateTime? StartTime { get; set; }
public DateTime? EndTime { get; set; }
public DateTime? UpdateTime { get; set; }
public TunedModel? TunedModel { get; set; }
public string? Experiment { get; set; }
public TuningDataStats? TuningDataStats { get; set; }
public StateTuningJob State { get; set; }
public SupervisedTuningSpec? SupervisedTuningSpec { get; set; }
public Status? Error { get; set; }
public string? Endpoint => TunedModel?.Endpoint;
public bool HasEnded => EndTime.HasValue;
}
public class SupervisedTuningSpec
{
public string TrainingDatasetUri { get; set; }
public string? ValidationDatasetUri { get; set; }
public HyperParameters? HyperParameters { get; set; }
}
public class TunedModel
{
public string Model { get; set; }
public string Endpoint { get; set; }
}
public class TuningDataStats
{
public SupervisedTuningDataStats SupervisedTuningDataStats { get; set; }
}
public class SupervisedTuningDataStats
{
public string TuninDatasetExampleCount { get; set; }
public string TotalTuningCharacterCount { get; set; }
public string TuningStepCount { get; set; }
public string TotalBillableTokenCount { get; set; }
public Distribution UserInputTokenDistribution { get; set; }
public Distribution UserOutputTokenDistribution { get; set; }
public Distribution UserMessagePerExampleDistribution { get; set; }
public List<ContentResponse> UserDatasetExamples { get; set; }
}
public class Distribution
{
public string Sum { get; set; }
public int Min { get; set; }
public int Max { get; set; }
public double Mean { get; set; }
public int Median { get; set; }
public int P5 { get; set; }
public int P95 { get; set; }
public List<DistributionBucket> Buckets { get; set; }
}
public class DistributionBucket
{
public int Count { get; set; }
public int Left { get; set; }
public int Right { get; set; }
}
public class GoogleSearchRetrieval
{
public DynamicRetrievalConfig? DynamicRetrievalConfig { get; set; }
public bool? DisableAttribution { get; set; }
public GoogleSearchRetrieval()
: this(DynamicRetrievalConfigMode.ModeDynamic, 0.3f)
{
}
public GoogleSearchRetrieval(DynamicRetrievalConfigMode mode, float dynamicThreshold)
{
DynamicRetrievalConfig = new DynamicRetrievalConfig
{
Mode = mode,
DynamicThreshold = dynamicThreshold
};
}
}
public class DynamicRetrievalConfig
{
public DynamicRetrievalConfigMode? Mode { get; set; }
public float? DynamicThreshold { get; set; }
}
public class GenerateContentRequest
{
public string Model { get; set; }
public List<Content> Contents { get; set; }
public GenerationConfig? GenerationConfig { get; set; }
public List<SafetySetting>? SafetySettings { get; set; }
public List<Tool>? Tools { get; set; }
public Content? SystemInstruction { get; set; }
public ToolConfig? ToolConfig { get; set; }
public string? CachedContent { get; set; }
public GenerateContentRequest()
{
}
public GenerateContentRequest(string prompt, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null, List<Tool>? tools = null, Content? systemInstruction = null, ToolConfig? toolConfig = null)
: this()
{
if (prompt == null)
{
throw new ArgumentNullException("prompt");
}
Contents = new List<Content>
{
new Content
{
Role = "user",
Parts = new List<IPart>
{
new TextData
{
Text = prompt
}
}
}
};
if (generationConfig != null)
{
GenerationConfig = generationConfig;
}
if (safetySettings != null)
{
SafetySettings = safetySettings;
}
if (tools != null)
{
Tools = tools;
}
if (systemInstruction != null)
{
SystemInstruction = systemInstruction;
}
if (toolConfig != null)
{
ToolConfig = toolConfig;
}
}
public GenerateContentRequest(List<IPart> parts, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null, List<Tool>? tools = null, Content? systemInstruction = null, ToolConfig? toolConfig = null)
: this()
{
if (parts == null)
{
throw new ArgumentNullException("parts");
}
Contents = new List<Content>
{
new Content
{
Parts = parts
}
};
if (generationConfig != null)
{
GenerationConfig = generationConfig;
}
if (safetySettings != null)
{
SafetySettings = safetySettings;
}
if (tools != null)
{
Tools = tools;
}
if (systemInstruction != null)
{
SystemInstruction = systemInstruction;
}
if (toolConfig != null)
{
ToolConfig = toolConfig;
}
}
public GenerateContentRequest(FileResource file, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null, List<Tool>? tools = null, Content? systemInstruction = null, ToolConfig? toolConfig = null)
: this()
{
if (file == null)
{
throw new ArgumentNullException("file");
}
Contents = new List<Content>
{
new Content
{
Role = "user",
Parts = new List<IPart>
{
new FileData
{
FileUri = file.Uri,
MimeType = file.MimeType
}
}
}
};
if (generationConfig != null)
{
GenerationConfig = generationConfig;
}
if (safetySettings != null)
{
SafetySettings = safetySettings;
}
if (tools != null)
{
Tools = tools;
}
if (systemInstruction != null)
{
SystemInstruction = systemInstruction;
}
if (toolConfig != null)
{
ToolConfig = toolConfig;
}
}
public GenerateContentRequest(List<Part> parts, GenerationConfig? generationConfig = null, List<SafetySetting>? safetySettings = null, List<Tool>? tools = null, Content? systemInstruction = null, ToolConfig? toolConfig = null)
: this()
{
if (parts == null)
{
throw new ArgumentNullException("parts");
}
Contents = new List<Content>
{
new Content
{
Parts = parts.Select((Part p) => (IPart)p).ToList()
}
};
if (generationConfig != null)
{
GenerationConfig = generationConfig;
}
if (safetySettings != null)
{
SafetySettings = safetySettings;
}
if (tools != null)
{
Tools = tools;
}
if (systemInstruction != null)
{
SystemInstruction = systemInstruction;
}
if (toolConfig != null)
{
ToolConfig = toolConfig;
}
}
public void AddContent(Content content)
{
Contents.Add(content);
}
public async Task AddMedia(string uri, string? mimeType = null, bool useOnline = false)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
if (mimeType == null)
{
mimeType = GenerativeAIExtensions.GetMimeType(uri);
}
if (useOnline)
{
Contents[0].Parts.Add(new FileData
{
FileUri = uri,
MimeType = mimeType
});
}
string data = ((!File.Exists(uri)) ? (await GenerativeAIExtensions.ReadImageFileBase64Async(uri)) : Convert.ToBase64String(await File.ReadAllBytesAsync(uri)));
GenerativeAIExtensions.GuardInlineDataMimeType(mimeType);
Contents[0].Parts.Add(new InlineData
{
MimeType = mimeType,
Data = data
});
}
public void AddMedia(FileResource file)
{
if (file == null)
{
throw new ArgumentNullException("file");
}
Contents[0].Parts.Add(new FileData
{
FileUri = file.Uri,
MimeType = file.MimeType
});
}
}
public class InlineData : IPart
{
public string Data { get; set; } = "";
public string MimeType { get; set; } = "";
}
public class FileResource
{
public string Name { get; set; }
public string? DisplayName { get; set; }
public string MimeType { get; set; }
public long SizeBytes { get; set; }
public DateTime CreateTime { get; set; }
public DateTime UpdateTime { get; set; }
public DateTime ExpirationTime { get; set; }
public string Sha256Hash { get; set; }
public string Uri { get; set; }
public StateFileResource State { get; set; }
public Status Error { get; set; }
public VideoMetadata Metadata { get; set; }
}
public class GenerateContentResponse
{
[JsonIgnore]
public string? Text
{
get
{
FinishReason? finishReason = Candidates?.FirstOrDefault()?.FinishReason;
bool flag;
if (finishReason.HasValue)
{
FinishReason valueOrDefault = finishReason.GetValueOrDefault();
if ((uint)(valueOrDefault - 2) <= 3u)
{
flag = true;
goto IL_004c;
}
}
flag = false;
goto IL_004c;
IL_004c:
if (flag)
{
return string.Empty;
}
return Candidates?.FirstOrDefault()?.Content?.Parts.FirstOrDefault()?.Text;
}
}
public List<Candidate>? Candidates { get; set; }
public PromptFeedback? PromptFeedback { get; set; }
public UsageMetadata? UsageMetadata { get; set; }
public string? ModelVersion { get; set; }
public override string ToString()
{
return Text ?? string.Empty;
}
}
public class UsageMetadata
{
public int PromptTokenCount { get; set; }
public int CandidatesTokenCount { get; set; }
public int TotalTokenCount { get; set; }
public int CachedContentTokenCount { get; set; }
}
public class Candidate
{
public ContentResponse? Content { get; set; }
public FinishReason? FinishReason { get; set; }
public string? FinishMessage { get; set; }
public int? Index { get; set; }
public List<SafetyRating>? SafetyRatings { get; set; }
public CitationMetadata? CitationMetadata { get; set; }
public FunctionCall? FunctionCall { get; set; }
public GroundingMetadata? GroundingMetadata { get; set; }
public int? TokenCount { get; set; }
public List<GroundingAttribution>? GroundingAttributions { get; set; }
public float? AvgLogprobs { get; set; }
public LogprobsResult? LogprobsResult { get; set; }
}
public class FunctionCall : IPart
{
public string Name { get; set; } = string.Empty;
public object? Args { get; set; }
}
public class LogprobsResult
{
public List<TopCandidates> TopCandidates { get; set; }
public List<LogprobsCandidate> ChosenCanditates { get; set; }
}
public class TopCandidates
{
public List<LogprobsCandidate> Candidates { get; set; }
}
public class LogprobsCandidate
{
public string Token { get; set; }
public int TokenId { get; set; }
public float LogProbability { get; set; }
}
public class RequestOptions
{
public Retry Retry;
public TimeSpan Timeout;
private RequestOptions()
{
Retry = new Retry();
Timeout = default(TimeSpan).Add(TimeSpan.FromSeconds(90.0));
}
public RequestOptions(Retry? retry, TimeSpan? timeout)
: this()
{
Retry = retry ?? Retry;
Timeout = timeout ?? Timeout;
}
}
public sealed class Credentials : ClientSecrets
{
private string _projectId;
public ClientSecrets Web { get; set; }
public ClientSecrets Installed { get; set; }
public string Account { get; set; }
public string RefreshToken { get; set; }
public string Type { get; set; }
public string UniverseDomain { get; set; }
public string ProjectId
{
get
{
return _projectId;
}
set
{
_projectId = value;
}
}
public string QuotaProjectId
{
get
{
return _projectId;
}
set
{
_projectId = value;
}
}
}
public class ClientSecrets
{
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string[] RedirectUris { get; set; }
public string AuthUri { get; set; }
public string AuthProviderX509CertUrl { get; set; }
public string TokenUri { get; set; }
}
public class ModelResponse
{
public string? Name { get; set; }
public string? BaseModelId { get; set; }
public string? Version { get; set; }
public string? DisplayName { get; set; }
public string? Description { get; set; }
public int? InputTokenLimit { get; set; }
public int? OutputTokenLimit { get; set; }
public List<string>? SupportedGenerationMethods { get; set; }
public float? Temperature { get; set; }
public float? TopP { get; set; }
public int? TopK { get; set; }
public State? State { get; set; }
public DateTime? CreateTime { get; set; }
public DateTime? UpdateTime { get; set; }
public TuningTask? TuningTask { get; set; }
public TunedModelSource? TunedModelSource { get; set; }
public string? BaseModel { get; set; }
}
public class GenerateAnswerRequest
{
public List<Content>? Contents { get; set; }
public AnswerStyle AnswerStyle { get; set; }
public List<SafetySetting>? SafetySettings { get; set; }
public GroundingPassages? InlinePassages { get; set; }
public SemanticRetrieverConfig? SemanticRetriever { get; set; }
public float? Temperature { get; set; }
public GenerateAnswerRequest()
{
}
public GenerateAnswerRequest(string prompt, AnswerStyle? answerStyle, List<SafetySetting>? safetySettings = null)
: this()
{
Contents = new List<Content>
{
new Content
{
Parts = new List<IPart>
{
new TextData
{
Text = prompt
}
}
}
};
AnswerStyle = answerStyle.GetValueOrDefault();
if (safetySettings != null)
{
SafetySettings = safetySettings;
}
}
}
public class StopCandidateException : Exception
{
public StopCandidateException()
{
}
public StopCandidateException(string? message)
: base(message)
{
}
public StopCandidateException(string? message, Exception? innerException)
: base(message, innerException)
{
}
public StopCandidateException(Candidate candidate)
: base(candidate.FinishMessage)
{
}
}
public class CreateTunedModelResponse
{
public string Name { get; set; }
public CreateTunedModelMetadata Metadata { get; set; }
}
public class CreateTunedModelRequest
{
public string DisplayName { get; set; }
public string BaseModel { get; set; }
public TuningTask TuningTask { get; set; }
public CreateTunedModelRequest()
{
TuningTask = new TuningTask
{
TrainingData = new TrainingData
{
Examples = new TuningExamples
{
Examples = new List<TuningExample>()
}
}
};
}
public CreateTunedModelRequest(string model, string name, List<TuningExample>? dataset = null, HyperParameters? parameters = null)
: this()
{
if (model == null)
{
throw new ArgumentNullException("model");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
BaseModel = model.SanitizeModelName();
DisplayName = name.Trim();
TuningTask.Hyperparameters = parameters;
TuningTask.TrainingData.Examples.Examples = dataset ?? new List<TuningExample>();
}
}
public class GroundingMetadata
{
public SearchEntryPoint? SearchEntryPoint { get; set; }
public List<GroundingAttribution>? GroundingAttributions { get; set; }
public List<string>? WebSearchQueries { get; set; }
public List<GroundingSupport>? GroundingSupports { get; set; }
public RetrievalMetadata? RetrievalMetadata { get; set; }
public List<GroundingChunk>? GroundingChunks { get; set; }
}
public class SearchEntryPoint
{
public string? RenderedContent { get; set; }
public byte[]? SdkBlob { get; set; }
}
public class GroundingAttribution
{
public int ConfidenceScore { get; set; }
public GroundingAttributionSegment? Segment { get; set; }
public GroundingAttributionWeb? Web { get; set; }
}
public class GroundingAttributionWeb
{
public string? Title { get; set; }
public string? Uri { get; set; }
}
public class GroundingAttributionSegment
{
public int StartIndex { get; internal set; }
public int EndIndex { get; internal set; }
public int PartIndex { get; internal set; }
}
public interface IPart
{
}
public class GenerateAnswerResponse
{
public string? Text
{
get
{
Candidate answer = Answer;
if (answer != null && answer.FinishReason.GetValueOrDefault() == FinishReason.Safety)
{
return string.Empty;
}
return Answer?.Content?.Parts?.FirstOrDefault()?.Text;
}
}
public Candidate Answer { get; set; }
public float AnswerableProbability { get; set; }
public PromptFeedback InputFeedback { get; set; }
public override string ToString()
{
return Text ?? string.Empty;
}
}
public class EmbedContentResponse
{
public List<Candidate>? Candidates { get; set; }
public ContentEmbedding? Embedding { get; set; }
public List<ContentEmbedding>? Embeddings { get; set; }
}
public sealed class CountTokensResponse
{
private int _totalTokens;
private int _totalCachedTokens;
public int TotalTokens
{
get
{
return _totalTokens;
}
set
{
_totalTokens = ((value >= 0) ? ((value < int.MaxValue) ? value : int.MaxValue) : 0);
}
}
public int TokenCount
{
get
{
return _totalTokens;
}
set
{
_totalTokens = ((value >= 0) ? ((value < int.MaxValue) ? value : int.MaxValue) : 0);
}
}
public int TotalBillableCharacters { get; set; }
public int CachedContentTokenCount
{
get
{
return _totalCachedTokens;
}
set
{
_totalCachedTokens = ((value >= 0) ? ((value < int.MaxValue) ? value : int.MaxValue) : 0);
}
}
}
public class ContentEmbedding
{
public List<float> Values { get; set; }
}
public class GenerateMessageRequest
{
public MessagePrompt Prompt { get; set; }
public float? Temperature { get; set; }
public float? TopP { get; set; }
public int? TopK { get; set; }
public int? CandidateCount { get; set; }
public GenerateMessageRequest()
{
Prompt = new MessagePrompt
{
Messages = new List<Message>()
};
}
public GenerateMessageRequest(string prompt)
: this()
{
Prompt.Messages.Add(new Message
{
Content = prompt
});
}
}
public class MessagePrompt
{
public string? Context { get; set; }
public List<Example>? Examples { get; set; }
public List<Message> Messages { get; set; }
}
public class Message
{
public string? Author { get; set; }
public string Content { get; set; }
public CitationMetadata? CitationMetadata { get; set; }
}
public class CitationMetadata
{
public CitationSource[]? Citations { get; internal set; }
}
public class CitationSource
{
public int? StartIndex { get; internal set; }
public int? EndIndex { get; internal set; }
public string? Uri { get; internal set; }
public string? Title { get; internal set; }
public string? License { get; internal set; }
public DateTimeOffset? PublicationDate { get; internal set; }
}
public class Example
{
public Message Input { get; set; }
public Message Output { get; set; }
}
public class PromptFeedback
{
public BlockedReason BlockReason { get; set; }
public List<SafetyRating>? SafetyRatings { get; set; }
public string BlockReasonMessage { get; set; } = "";
}
public class FileData : IPart
{
public string FileUri { get; set; } = string.Empty;
public string MimeType { get; set; } = string.Empty;
}
public class GroundingSupport
{
public Segment? Segment { get; set; }
public List<int>? GroundingChunkIndices { get; set; }
public List<float>? ConfidenceScores { get; set; }
}
public class Segment
{
public string? Text { get; set; }
public int? StartIndex { get; set; }
public int? PartIndex { get; set; }
public int? EndIndex { get; set; }
}
public class RetrievalMetadata
{
public float? GoogleSearchDynamicRetrievalScore { get; set; }
}
public class GroundingChunk
{
public Web? Web { get; set; }
}
public class Web
{
public string? Uri { get; set; }
public string? Title { get; set; }
}
public class TuningExample
{
public string? TextInput { get; set; }
public string Output { get; set; }
}
public class HyperParameters
{
public int? BatchSize { get; set; }
public float? LearningRate { get; set; }
public float? LearningRateMultiplier { get; set; }
public int? EpochCount { get; set; }
public AdapterSize? AdapterSize { get; set; }
}
public class TuningTask
{
public DateTime? StartTime { get; set; }
public DateTime? CompleteTime { get; set; }
public List<TuningSnapshot>? Snapshots { get; set; }
public TrainingData? TrainingData { get; set; }
public HyperParameters? Hyperparameters { get; set; }
}
public class TuningSnapshot
{
public int Step { get; set; }
public int? Epoch { get; set; }
public float? MeanLoss { get; set; }
public DateTime ComputeTime { get; set; }
}
public class TrainingData
{
public TuningExamples? Examples { get; set; }
}
public class TuningExamples
{
public List<TuningExample> Examples { get; set; }
}
public class CreateTunedModelMetadata
{
public string Type { get; set; }
public int TotalSteps { get; set; }
public string TunedModel { get; set; }
}
public class GroundingPassages
{
public List<GroundingPassage> Passages { get; set; }
}
public class GroundingPassage
{
public string Id { get; set; }
public Content Content { get; set; }
}
public class SemanticRetrieverConfig
{
public string Source { get; set; }
public Content Query { get; set; }
public List<MetadataFilter>? MetadataFilters { get; set; }
public int? MaxChunkCount { get; set; }
public float? MinimumRelevanceScore { get; set; }
}
public class MetadataFilter
{
public string Key { get; set; }
public List<Condition> Conditions { get; set; }
}
public class Condition
{
public Operator Operation { get; set; }
public string? StringValue { get; set; }
public float? NumericValue { get; set; }
}
public class TunedModelSource
{
public string TunedModel { get; set; }
public string BaseModel { get; set; }
}
public class Retry
{
public int Initial { get; set; }
public int Multiplies { get; set; }
public int Maximum { get; set; }
public int Timeout { get; set; }
}
public class Status
{
public int Code { get; set; }
public string Message { get; set; }
public List<dynamic> Details { get; set; }
}
public class VideoMetadata : IPart
{
public string? VideoDuration { get; set; }
public Duration StartOffset { get; set; }
public Duration EndOffset { get; set; }
}
public class Duration
{
public int Seconds { get; set; }
public int Nanos { get; set; }
}
#region ENUM
[JsonConverter(typeof(JsonStringEnumConverter<Outcome>))]
public enum Outcome
{
OutcomeUnspecified = 1,
OutcomeOk,
OutcomeFailed,
OutcomeDeadlineExceeded
}
[JsonConverter(typeof(JsonStringEnumConverter<Language>))]
public enum Language
{
LanguageUnspecified,
Python
}
[JsonConverter(typeof(JsonStringEnumConverter<HarmBlockThreshold>))]
public enum HarmBlockThreshold
{
HarmBlockThresholdUnspecified,
BlockLowAndAbove,
BlockMediumAndAbove,
BlockOnlyHigh,
BlockNone,
None
}
[JsonConverter(typeof(JsonStringEnumConverter<ParameterType>))]
public enum FunctionCallingMode
{
ModeUnspecified,
Auto,
Any,
None
}
[JsonConverter(typeof(JsonStringEnumConverter<StateTuningJob>))]
public enum StateTuningJob
{
StateUnspecified,
JobStateRunning,
JobStatePending,
JobStateFailed,
JobStateCancelled
}
[JsonConverter(typeof(JsonStringEnumConverter<DynamicRetrievalConfigMode>))]
public enum DynamicRetrievalConfigMode
{
ModeUnspecified,
ModeDynamic
}
[JsonConverter(typeof(JsonStringEnumConverter<FinishReason>))]
public enum FinishReason
{
FinishReasonUnspecified,
Stop,
MaxTokens,
Safety,
Recitation,
Other,
Blocklist,
ProhibitedContent,
Spii,
MalformedFunctionCall,
Language
}
[JsonConverter(typeof(JsonStringEnumConverter<AnswerStyle>))]
public enum AnswerStyle
{
AnswerStyleUnspecified,
Abstractive,
Extractive,
Verbose
}
[JsonConverter(typeof(JsonStringEnumConverter<ParameterType>))]
public enum TaskType
{
TaskTypeUnspecified,
RetrievalQuery,
RetrievalDocument,
SemanticSimilarity,
Classification,
Clustering,
QuestionAnswering,
FactVerification
}
[JsonConverter(typeof(JsonStringEnumConverter<ParameterType>))]
public enum ParameterType
{
TypeUnspecified,
String,
Number,
Integer,
Boolean,
Array,
Object
}
[JsonConverter(typeof(JsonStringEnumConverter<BlockedReason>))]
public enum BlockedReason
{
BlockedReasonUnspecified,
Safety,
Other,
Blocklist,
ProhibitedContent
}
[JsonConverter(typeof(JsonStringEnumConverter<HarmCategory>))]
public enum HarmCategory
{
HarmCategoryUnspecified = 0,
HarmCategoryHateSpeech = 1,
HarmCategoryDangerousContent = 2,
HarmCategoryHarassment = 3,
HarmCategorySexuallyExplicit = 4,
HarmCategoryCivicIntegrity = 5,
[Obsolete("This value is related to PaLM 2 models and features.")]
HarmCategoryDerogatory = 101,
[Obsolete("This value is related to PaLM 2 models and features.")]
HarmCategoryToxicity = 102,
[Obsolete("This value is related to PaLM 2 models and features.")]
HarmCategoryViolence = 103,
[Obsolete("This value is related to PaLM 2 models and features.")]
HarmCategorySexual = 104,
[Obsolete("This value is related to PaLM 2 models and features.")]
HarmCategoryMedical = 105,
[Obsolete("This value is related to PaLM 2 models and features.")]
HarmCategoryDangerous = 106
}
[JsonConverter(typeof(JsonStringEnumConverter<HarmProbability>))]
public enum HarmProbability
{
HarmProbabilityUnspecified,
Negligible,
Low,
Medium,
High
}
[JsonConverter(typeof(JsonStringEnumConverter<HarmSeverity>))]
public enum HarmSeverity
{
HarmSeverityUnspecified,
HarmSeverityNegligible,
HarmSeverityLow,
HarmSeverityMedium,
HarmSeverityHigh
}
[JsonConverter(typeof(JsonStringEnumConverter<AdapterSize>))]
public enum AdapterSize
{
AdapterSizeUnspecified,
AdapterSizeOne,
AdapterSizeFour,
AdapterSizeEight,
AdapterSizeSixteen
}
[JsonConverter(typeof(JsonStringEnumConverter<Operator>))]
public enum Operator
{
OperatorUnspecified,
Less,
LessEqual,
Equal,
GreaterEqual,
Greater,
NotEqual,
Includes,
Excludes
}
[JsonConverter(typeof(JsonStringEnumConverter<State>))]
public enum State
{
StateUnspecified,
Creating,
Active,
Failed
}
[JsonConverter(typeof(JsonStringEnumConverter<StateFileResource>))]
public enum StateFileResource
{
StateUnspecified,
Processing,
Active,
Failed
}
#endregion
}