|
| 1 | +/* |
| 2 | + * Copyright 2026 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.Linq; |
| 20 | +using System.Threading; |
| 21 | +using System.Threading.Tasks; |
| 22 | +using Firebase.AI.Internal; |
| 23 | + |
| 24 | +namespace Firebase.AI |
| 25 | +{ |
| 26 | + // Because of how the SDK is distributed, 'internal' isn't really internal |
| 27 | + // So hide the internal calls from generativeModel that are needed, they are passed in instead |
| 28 | + using GenerateContentFunc = Func<string, IDictionary<string, object>, |
| 29 | + IEnumerable<ModelContent>, IEnumerable<ITemplateTool>, |
| 30 | + TemplateToolConfig?, CancellationToken, |
| 31 | + Task<GenerateContentResponse>>; |
| 32 | + using GenerateContentStreamFunc = Func<string, IDictionary<string, object>, |
| 33 | + IEnumerable<ModelContent>, IEnumerable<ITemplateTool>, |
| 34 | + TemplateToolConfig?, CancellationToken, |
| 35 | + IAsyncEnumerable<GenerateContentResponse>>; |
| 36 | + |
| 37 | + /// <summary> |
| 38 | + /// An object that represents a back-and-forth chat with a template model, capturing the history |
| 39 | + /// and saving the context in memory between each message sent. |
| 40 | + /// </summary> |
| 41 | + public class TemplateChatSession |
| 42 | + { |
| 43 | + private readonly TemplateGenerativeModel generativeModel; |
| 44 | + private readonly GenerateContentFunc generateContentFunc; |
| 45 | + private readonly GenerateContentStreamFunc generateContentStreamFunc; |
| 46 | + private readonly string templateId; |
| 47 | + private readonly Dictionary<string, object> inputs; |
| 48 | + private readonly List<ModelContent> chatHistory; |
| 49 | + private readonly List<ITemplateTool> tools; |
| 50 | + private readonly TemplateToolConfig? toolConfig; |
| 51 | + |
| 52 | + /// <summary> |
| 53 | + /// The previous content from the chat that has been successfully sent and received from the |
| 54 | + /// model. This will be provided to the model for each message sent as context for the discussion. |
| 55 | + /// </summary> |
| 56 | + public IReadOnlyList<ModelContent> History => chatHistory; |
| 57 | + |
| 58 | + // Note: No public constructor, get one through GenerativeModel.StartChat |
| 59 | + private TemplateChatSession( |
| 60 | + TemplateGenerativeModel model, |
| 61 | + GenerateContentFunc generateContentFunc, |
| 62 | + GenerateContentStreamFunc generateContentStreamFunc, |
| 63 | + string templateId, |
| 64 | + IDictionary<string, object> inputs, |
| 65 | + IEnumerable<ModelContent> initialHistory, |
| 66 | + IEnumerable<ITemplateTool> tools, |
| 67 | + TemplateToolConfig? toolConfig) |
| 68 | + { |
| 69 | + generativeModel = model; |
| 70 | + this.generateContentFunc = generateContentFunc; |
| 71 | + this.templateId = templateId; |
| 72 | + if (inputs != null) |
| 73 | + { |
| 74 | + this.inputs = new Dictionary<string, object>(inputs); |
| 75 | + } |
| 76 | + else |
| 77 | + { |
| 78 | + this.inputs = new Dictionary<string, object>(); |
| 79 | + } |
| 80 | + chatHistory = initialHistory?.ToList() ?? new List<ModelContent>(); |
| 81 | + this.tools = tools?.ToList() ?? new List<ITemplateTool>(); |
| 82 | + this.toolConfig = toolConfig; |
| 83 | + } |
| 84 | + |
| 85 | + /// <summary> |
| 86 | + /// Intended for internal use only. |
| 87 | + /// Use `TemplateGenerativeModel.StartChat` instead to ensure proper initialization. |
| 88 | + /// </summary> |
| 89 | + internal static TemplateChatSession InternalCreateChat( |
| 90 | + TemplateGenerativeModel model, |
| 91 | + GenerateContentFunc generateContentFunc, |
| 92 | + GenerateContentStreamFunc generateContentStreamFunc, |
| 93 | + string templateId, |
| 94 | + IDictionary<string, object> inputs, |
| 95 | + IEnumerable<ModelContent> initialHistory, |
| 96 | + IEnumerable<ITemplateTool> tools, |
| 97 | + TemplateToolConfig? toolConfig) |
| 98 | + { |
| 99 | + return new TemplateChatSession( |
| 100 | + model, generateContentFunc, generateContentStreamFunc, templateId, inputs, |
| 101 | + initialHistory, tools, toolConfig); |
| 102 | + } |
| 103 | + |
| 104 | + /// <summary> |
| 105 | + /// Sends a message using the existing history of this chat as context. |
| 106 | + /// </summary> |
| 107 | + /// <param name="content">The input given to the model as a prompt.</param> |
| 108 | + /// <param name="cancellationToken">An optional token to cancel the operation.</param> |
| 109 | + /// <returns>The model's response if no error occurred.</returns> |
| 110 | + public Task<GenerateContentResponse> SendMessageAsync( |
| 111 | + ModelContent content, CancellationToken cancellationToken = default) |
| 112 | + { |
| 113 | + return SendMessageAsyncInternal(content, cancellationToken); |
| 114 | + } |
| 115 | + |
| 116 | + /// <summary> |
| 117 | + /// Sends a message using the existing history of this chat as context. |
| 118 | + /// </summary> |
| 119 | + /// <param name="text">The text given to the model as a prompt.</param> |
| 120 | + /// <param name="cancellationToken">An optional token to cancel the operation.</param> |
| 121 | + /// <returns>The model's response if no error occurred.</returns> |
| 122 | + public Task<GenerateContentResponse> SendMessageAsync( |
| 123 | + string text, CancellationToken cancellationToken = default) |
| 124 | + { |
| 125 | + return SendMessageAsync(ModelContent.Text(text), cancellationToken); |
| 126 | + } |
| 127 | + |
| 128 | + private async Task<GenerateContentResponse> SendMessageAsyncInternal( |
| 129 | + ModelContent content, CancellationToken cancellationToken) |
| 130 | + { |
| 131 | + // Make sure that the request is set to to role "user". |
| 132 | + ModelContent fixedRequest = FirebaseAIExtensions.ConvertToUser(content); |
| 133 | + // Set up the context to send in the history and request |
| 134 | + List<ModelContent> fullRequest = new(chatHistory) { fixedRequest }; |
| 135 | + |
| 136 | + // Note: GenerateContentAsync can throw exceptions if there was a problem, but |
| 137 | + // we allow it to just be passed back to the user. |
| 138 | + GenerateContentResponse response = await generateContentFunc( |
| 139 | + templateId, inputs, fullRequest, tools, toolConfig, cancellationToken); |
| 140 | + |
| 141 | + // Only after getting a valid response, add both to the history for later. |
| 142 | + // But either way pass the response along to the user. |
| 143 | + if (response.Candidates.Any()) |
| 144 | + { |
| 145 | + ModelContent responseContent = response.Candidates.First().Content; |
| 146 | + |
| 147 | + chatHistory.Add(fixedRequest); |
| 148 | + chatHistory.Add(responseContent.ConvertToModel()); |
| 149 | + } |
| 150 | + |
| 151 | + return response; |
| 152 | + } |
| 153 | + } |
| 154 | +} |
0 commit comments