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