|
14 | 14 | * limitations under the License.
|
15 | 15 | */
|
16 | 16 |
|
| 17 | +// For now, using this to hide some functions causing problems with the build. |
| 18 | +#define HIDE_IASYNCENUMERABLE |
| 19 | + |
17 | 20 | using System;
|
18 | 21 | using System.Collections.Generic;
|
| 22 | +using System.Linq; |
| 23 | +using System.Net.Http; |
| 24 | +using System.Text; |
19 | 25 | using System.Threading.Tasks;
|
| 26 | +using Google.MiniJSON; |
20 | 27 |
|
21 | 28 | namespace Firebase.VertexAI {
|
22 | 29 |
|
| 30 | +/// <summary> |
| 31 | +/// A type that represents a remote multimodal model (like Gemini), with the ability to generate |
| 32 | +/// content based on various input types. |
| 33 | +/// </summary> |
23 | 34 | public class GenerativeModel {
|
| 35 | + private FirebaseApp _firebaseApp; |
| 36 | + |
| 37 | + // Various setting fields provided by the user. |
| 38 | + private string _location; |
| 39 | + private string _modelName; |
| 40 | + private GenerationConfig? _generationConfig; |
| 41 | + private SafetySetting[] _safetySettings; |
| 42 | + private Tool[] _tools; |
| 43 | + private ToolConfig? _toolConfig; |
| 44 | + private ModelContent? _systemInstruction; |
| 45 | + private RequestOptions? _requestOptions; |
| 46 | + |
| 47 | + HttpClient _httpClient; |
| 48 | + |
| 49 | + internal GenerativeModel(FirebaseApp firebaseApp, |
| 50 | + string location, |
| 51 | + string modelName, |
| 52 | + GenerationConfig? generationConfig = null, |
| 53 | + SafetySetting[] safetySettings = null, |
| 54 | + Tool[] tools = null, |
| 55 | + ToolConfig? toolConfig = null, |
| 56 | + ModelContent? systemInstruction = null, |
| 57 | + RequestOptions? requestOptions = null) { |
| 58 | + _firebaseApp = firebaseApp; |
| 59 | + _location = location; |
| 60 | + _modelName = modelName; |
| 61 | + _generationConfig = generationConfig; |
| 62 | + _safetySettings = safetySettings; |
| 63 | + _tools = tools; |
| 64 | + _toolConfig = toolConfig; |
| 65 | + _systemInstruction = systemInstruction; |
| 66 | + _requestOptions = requestOptions; |
| 67 | + |
| 68 | + // Create a HttpClient using the timeout requested, or the default one. |
| 69 | + _httpClient = new HttpClient() { |
| 70 | + Timeout = requestOptions?.Timeout ?? RequestOptions.DefaultTimeout |
| 71 | + }; |
| 72 | + } |
| 73 | + |
| 74 | +#region Public API |
| 75 | + /// <summary> |
| 76 | + /// Generates new content from input `ModelContent` given to the model as a prompt. |
| 77 | + /// </summary> |
| 78 | + /// <param name="content">The input(s) given to the model as a prompt.</param> |
| 79 | + /// <returns>The generated content response from the model.</returns> |
| 80 | + /// <exception cref="VertexAIException">Thrown when an error occurs during content generation.</exception> |
24 | 81 | public Task<GenerateContentResponse> GenerateContentAsync(
|
25 | 82 | params ModelContent[] content) {
|
26 |
| - throw new NotImplementedException(); |
| 83 | + return GenerateContentAsync((IEnumerable<ModelContent>)content); |
27 | 84 | }
|
| 85 | + /// <summary> |
| 86 | + /// Generates new content from input text given to the model as a prompt. |
| 87 | + /// </summary> |
| 88 | + /// <param name="content">The text given to the model as a prompt.</param> |
| 89 | + /// <returns>The generated content response from the model.</returns> |
| 90 | + /// <exception cref="VertexAIException">Thrown when an error occurs during content generation.</exception> |
28 | 91 | public Task<GenerateContentResponse> GenerateContentAsync(
|
29 |
| - IEnumerable<ModelContent> content) { |
30 |
| - throw new NotImplementedException(); |
| 92 | + string text) { |
| 93 | + return GenerateContentAsync(new ModelContent[] { ModelContent.Text(text) }); |
31 | 94 | }
|
| 95 | + /// <summary> |
| 96 | + /// Generates new content from input `ModelContent` given to the model as a prompt. |
| 97 | + /// </summary> |
| 98 | + /// <param name="content">The input(s) given to the model as a prompt.</param> |
| 99 | + /// <returns>The generated content response from the model.</returns> |
| 100 | + /// <exception cref="VertexAIException">Thrown when an error occurs during content generation.</exception> |
32 | 101 | public Task<GenerateContentResponse> GenerateContentAsync(
|
33 |
| - string text) { |
34 |
| - throw new NotImplementedException(); |
| 102 | + IEnumerable<ModelContent> content) { |
| 103 | + return GenerateContentAsyncInternal(content); |
35 | 104 | }
|
36 | 105 |
|
37 |
| -// The build logic isn't able to resolve IAsyncEnumerable for some reason, even |
38 |
| -// though it is usable in Unity 2021.3. Will need to investigate further. |
39 |
| -/* |
| 106 | +#if !HIDE_IASYNCENUMERABLE |
40 | 107 | public IAsyncEnumerable<GenerateContentResponse> GenerateContentStreamAsync(
|
41 | 108 | params ModelContent[] content) {
|
42 |
| - throw new NotImplementedException(); |
| 109 | + return GenerateContentStreamAsync((IEnumerable<ModelContent>)content); |
43 | 110 | }
|
44 | 111 | public IAsyncEnumerable<GenerateContentResponse> GenerateContentStreamAsync(
|
45 |
| - IEnumerable<ModelContent> content) { |
46 |
| - throw new NotImplementedException(); |
| 112 | + string text) { |
| 113 | + return GenerateContentStreamAsync(new ModelContent[] { ModelContent.Text(text) }); |
47 | 114 | }
|
48 | 115 | public IAsyncEnumerable<GenerateContentResponse> GenerateContentStreamAsync(
|
49 |
| - string text) { |
50 |
| - throw new NotImplementedException(); |
| 116 | + IEnumerable<ModelContent> content) { |
| 117 | + return GenerateContentStreamAsyncInternal(content); |
51 | 118 | }
|
52 |
| -*/ |
| 119 | +#endif |
53 | 120 |
|
54 | 121 | public Task<CountTokensResponse> CountTokensAsync(
|
55 | 122 | params ModelContent[] content) {
|
56 |
| - throw new NotImplementedException(); |
| 123 | + return CountTokensAsync((IEnumerable<ModelContent>)content); |
57 | 124 | }
|
58 | 125 | public Task<CountTokensResponse> CountTokensAsync(
|
59 |
| - IEnumerable<ModelContent> content) { |
60 |
| - throw new NotImplementedException(); |
| 126 | + string text) { |
| 127 | + return CountTokensAsync(new ModelContent[] { ModelContent.Text(text) }); |
61 | 128 | }
|
62 | 129 | public Task<CountTokensResponse> CountTokensAsync(
|
63 |
| - string text) { |
64 |
| - throw new NotImplementedException(); |
| 130 | + IEnumerable<ModelContent> content) { |
| 131 | + return CountTokensAsyncInternal(content); |
65 | 132 | }
|
66 | 133 |
|
67 | 134 | public Chat StartChat(params ModelContent[] history) {
|
68 |
| - throw new NotImplementedException(); |
| 135 | + return StartChat((IEnumerable<ModelContent>)history); |
69 | 136 | }
|
70 | 137 | public Chat StartChat(IEnumerable<ModelContent> history) {
|
| 138 | + // TODO: Implementation |
71 | 139 | throw new NotImplementedException();
|
72 | 140 | }
|
| 141 | +#endregion |
| 142 | + |
| 143 | + private async Task<GenerateContentResponse> GenerateContentAsyncInternal( |
| 144 | + IEnumerable<ModelContent> content) { |
| 145 | + string bodyJson = ModelContentsToJson(content); |
| 146 | + |
| 147 | + HttpRequestMessage request = new(HttpMethod.Post, GetURL() + ":generateContent"); |
| 148 | + |
| 149 | + // Set the request headers |
| 150 | + request.Headers.Add("x-goog-api-key", _firebaseApp.Options.ApiKey); |
| 151 | + request.Headers.Add("x-goog-api-client", "genai-csharp/0.1.0"); |
| 152 | + |
| 153 | + // Set the content |
| 154 | + request.Content = new StringContent(bodyJson, Encoding.UTF8, "application/json"); |
| 155 | + |
| 156 | + HttpResponseMessage response = await _httpClient.SendAsync(request); |
| 157 | + // TODO: Convert any timeout exception into a VertexAI equivalent |
| 158 | + // TODO: Convert any HttpRequestExceptions, see: |
| 159 | + // https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.sendasync?view=net-9.0 |
| 160 | + // https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpresponsemessage.ensuresuccessstatuscode?view=net-9.0 |
| 161 | + response.EnsureSuccessStatusCode(); |
| 162 | + |
| 163 | + string result = await response.Content.ReadAsStringAsync(); |
| 164 | + |
| 165 | + return GenerateContentResponse.FromJson(result); |
| 166 | + } |
73 | 167 |
|
74 |
| - // Note: No public constructor, get one through VertexAI.GetGenerativeModel |
| 168 | +#if !HIDE_IASYNCENUMERABLE |
| 169 | + private async IAsyncEnumerable<GenerateContentResponse> GenerateContentStreamAsyncInternal( |
| 170 | + IEnumerable<ModelContent> content) { |
| 171 | + // TODO: Implementation |
| 172 | + await Task.CompletedTask; |
| 173 | + yield return new GenerateContentResponse(); |
| 174 | + throw new NotImplementedException(); |
| 175 | + } |
| 176 | +#endif |
| 177 | + |
| 178 | + private async Task<CountTokensResponse> CountTokensAsyncInternal( |
| 179 | + IEnumerable<ModelContent> content) { |
| 180 | + // TODO: Implementation |
| 181 | + await Task.CompletedTask; |
| 182 | + throw new NotImplementedException(); |
| 183 | + } |
| 184 | + |
| 185 | + private string GetURL() { |
| 186 | + return "https://firebaseml.googleapis.com/v2beta" + |
| 187 | + "/projects/" + _firebaseApp.Options.ProjectId + |
| 188 | + "/locations/" + _location + |
| 189 | + "/publishers/google/models/" + _modelName; |
| 190 | + } |
| 191 | + |
| 192 | + private string ModelContentsToJson(IEnumerable<ModelContent> contents) { |
| 193 | + Dictionary<string, object> jsonDict = new() { |
| 194 | + // Convert the Contents into a list of Json dictionaries |
| 195 | + ["contents"] = contents.Select(c => c.ToJson()).ToList() |
| 196 | + }; |
| 197 | + // TODO: All the other settings |
| 198 | + |
| 199 | + return Json.Serialize(jsonDict); |
| 200 | + } |
75 | 201 | }
|
76 | 202 |
|
77 | 203 | }
|
0 commit comments