|
| 1 | +/* |
| 2 | + * Copyright 2025 Google LLC |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +using System; |
| 18 | +using System.Collections.Generic; |
| 19 | +using System.Net.Http; |
| 20 | +using System.Text; |
| 21 | +using System.Threading; |
| 22 | +using System.Threading.Tasks; |
| 23 | +using Google.MiniJSON; |
| 24 | +using Firebase.AI.Internal; |
| 25 | +using System.Linq; |
| 26 | +using System.Runtime.CompilerServices; |
| 27 | +using System.IO; |
| 28 | + |
| 29 | +namespace Firebase.AI |
| 30 | +{ |
| 31 | + /// <summary> |
| 32 | + /// A type that represents a remote multimodal model (like Gemini), with the ability to generate |
| 33 | + /// content based on defined server prompt templates. |
| 34 | + /// </summary> |
| 35 | + public class TemplateGenerativeModel |
| 36 | + { |
| 37 | + private readonly FirebaseApp _firebaseApp; |
| 38 | + private readonly FirebaseAI.Backend _backend; |
| 39 | + |
| 40 | + private readonly HttpClient _httpClient; |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Intended for internal use only. |
| 44 | + /// Use `FirebaseAI.GetTemplateGenerativeModel` instead to ensure proper |
| 45 | + /// initialization and configuration of the `TemplateGenerativeModel`. |
| 46 | + /// </summary> |
| 47 | + internal TemplateGenerativeModel(FirebaseApp firebaseApp, |
| 48 | + FirebaseAI.Backend backend, |
| 49 | + RequestOptions? requestOptions = null) |
| 50 | + { |
| 51 | + _firebaseApp = firebaseApp; |
| 52 | + _backend = backend; |
| 53 | + |
| 54 | + // Create a HttpClient using the timeout requested, or the default one. |
| 55 | + _httpClient = new HttpClient() |
| 56 | + { |
| 57 | + Timeout = requestOptions?.Timeout ?? RequestOptions.DefaultTimeout |
| 58 | + }; |
| 59 | + } |
| 60 | + |
| 61 | + /// <summary> |
| 62 | + /// Generates new content by calling into a server prompt template. |
| 63 | + /// </summary> |
| 64 | + /// <param name="templateId">The id of the server prompt template to use.</param> |
| 65 | + /// <param name="inputs">Any input parameters expected by the server prompt template.</param> |
| 66 | + /// <param name="cancellationToken">An optional token to cancel the operation.</param> |
| 67 | + /// <returns>The generated content response from the model.</returns> |
| 68 | + /// <exception cref="HttpRequestException">Thrown when an error occurs during content generation.</exception> |
| 69 | + public Task<GenerateContentResponse> GenerateContentAsync( |
| 70 | + string templateId, IDictionary<string, object> inputs, |
| 71 | + CancellationToken cancellationToken = default) |
| 72 | + { |
| 73 | + return GenerateContentAsyncInternal(templateId, inputs, null, cancellationToken); |
| 74 | + } |
| 75 | + |
| 76 | + /// <summary> |
| 77 | + /// Generates new content as a stream by calling into a server prompt template. |
| 78 | + /// </summary> |
| 79 | + /// <param name="templateId">The id of the server prompt template to use.</param> |
| 80 | + /// <param name="inputs">Any input parameters expected by the server prompt template.</param> |
| 81 | + /// <param name="cancellationToken">An optional token to cancel the operation.</param> |
| 82 | + /// <returns>A stream of generated content responses from the model.</returns> |
| 83 | + /// <exception cref="HttpRequestException">Thrown when an error occurs during content generation.</exception> |
| 84 | + public IAsyncEnumerable<GenerateContentResponse> GenerateContentStreamAsync( |
| 85 | + string templateId, IDictionary<string, object> inputs, |
| 86 | + CancellationToken cancellationToken = default) |
| 87 | + { |
| 88 | + return GenerateContentStreamAsyncInternal(templateId, inputs, null, cancellationToken); |
| 89 | + } |
| 90 | + |
| 91 | + private string MakeGenerateContentRequest(IDictionary<string, object> inputs, |
| 92 | + IEnumerable<ModelContent> chatHistory) |
| 93 | + { |
| 94 | + var jsonDict = new Dictionary<string, object>() |
| 95 | + { |
| 96 | + ["inputs"] = inputs |
| 97 | + }; |
| 98 | + if (chatHistory != null) |
| 99 | + { |
| 100 | + jsonDict["history"] = chatHistory.Select(t => t.ToJson()).ToList(); |
| 101 | + } |
| 102 | + return Json.Serialize(jsonDict); |
| 103 | + } |
| 104 | + |
| 105 | + private async Task<GenerateContentResponse> GenerateContentAsyncInternal( |
| 106 | + string templateId, IDictionary<string, object> inputs, |
| 107 | + IEnumerable<ModelContent> chatHistory, |
| 108 | + CancellationToken cancellationToken) |
| 109 | + { |
| 110 | + HttpRequestMessage request = new(HttpMethod.Post, |
| 111 | + HttpHelpers.GetTemplateURL(_firebaseApp, _backend, templateId) + ":templateGenerateContent"); |
| 112 | + |
| 113 | + // Set the request headers |
| 114 | + await HttpHelpers.SetRequestHeaders(request, _firebaseApp); |
| 115 | + |
| 116 | + // Set the content |
| 117 | + string bodyJson = MakeGenerateContentRequest(inputs, chatHistory); |
| 118 | + request.Content = new StringContent(bodyJson, Encoding.UTF8, "application/json"); |
| 119 | + |
| 120 | +#if FIREBASE_LOG_REST_CALLS |
| 121 | + UnityEngine.Debug.Log("Request:\n" + bodyJson); |
| 122 | +#endif |
| 123 | + |
| 124 | + var response = await _httpClient.SendAsync(request, cancellationToken); |
| 125 | + await HttpHelpers.ValidateHttpResponse(response); |
| 126 | + |
| 127 | + string result = await response.Content.ReadAsStringAsync(); |
| 128 | + |
| 129 | +#if FIREBASE_LOG_REST_CALLS |
| 130 | + UnityEngine.Debug.Log("Response:\n" + result); |
| 131 | +#endif |
| 132 | + |
| 133 | + return GenerateContentResponse.FromJson(result, _backend.Provider); |
| 134 | + } |
| 135 | + |
| 136 | + private async IAsyncEnumerable<GenerateContentResponse> GenerateContentStreamAsyncInternal( |
| 137 | + string templateId, IDictionary<string, object> inputs, |
| 138 | + IEnumerable<ModelContent> chatHistory, |
| 139 | + [EnumeratorCancellation] CancellationToken cancellationToken) |
| 140 | + { |
| 141 | + HttpRequestMessage request = new(HttpMethod.Post, |
| 142 | + HttpHelpers.GetTemplateURL(_firebaseApp, _backend, templateId) + ":templateStreamGenerateContent?alt=sse"); |
| 143 | + |
| 144 | + // Set the request headers |
| 145 | + await HttpHelpers.SetRequestHeaders(request, _firebaseApp); |
| 146 | + |
| 147 | + // Set the content |
| 148 | + string bodyJson = MakeGenerateContentRequest(inputs, chatHistory); |
| 149 | + request.Content = new StringContent(bodyJson, Encoding.UTF8, "application/json"); |
| 150 | + |
| 151 | +#if FIREBASE_LOG_REST_CALLS |
| 152 | + UnityEngine.Debug.Log("Request:\n" + bodyJson); |
| 153 | +#endif |
| 154 | + |
| 155 | + var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken); |
| 156 | + await HttpHelpers.ValidateHttpResponse(response); |
| 157 | + |
| 158 | + // We are expecting a Stream as the response, so handle that. |
| 159 | + using var stream = await response.Content.ReadAsStreamAsync(); |
| 160 | + using var reader = new StreamReader(stream); |
| 161 | + |
| 162 | + string line; |
| 163 | + while ((line = await reader.ReadLineAsync()) != null) |
| 164 | + { |
| 165 | + // Only pass along strings that begin with the expected prefix. |
| 166 | + if (line.StartsWith(HttpHelpers.StreamPrefix)) |
| 167 | + { |
| 168 | +#if FIREBASE_LOG_REST_CALLS |
| 169 | + UnityEngine.Debug.Log("Streaming Response:\n" + line); |
| 170 | +#endif |
| 171 | + |
| 172 | + yield return GenerateContentResponse.FromJson(line[HttpHelpers.StreamPrefix.Length..], _backend.Provider); |
| 173 | + } |
| 174 | + } |
| 175 | + } |
| 176 | + } |
| 177 | +} |
0 commit comments