-
Notifications
You must be signed in to change notification settings - Fork 54
[Firebase AI] Add simplified object generation #1423
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
a-maurice
wants to merge
3
commits into
main
Choose a base branch
from
am-generate_object
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| /* | ||
| * Copyright 2026 Google LLC | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| using System; | ||
| using System.Collections; | ||
| using System.Collections.Generic; | ||
| using System.Reflection; | ||
| using Google.MiniJSON; | ||
|
|
||
| namespace Firebase.AI | ||
| { | ||
| /// <summary> | ||
| /// Interface to define a method to construct the object from a Dictionary<string, object>. | ||
| /// | ||
| /// The Firebase AI Logic SDK by default will attempt to use reflection when deserializing objects, | ||
| /// like in `GenerateObjectResponse`, but this allows developers to override that logic with their own. | ||
| /// </summary> | ||
| public interface IFirebaseDeserializable | ||
| { | ||
| /// <summary> | ||
| /// Populate an object's fields with the given dictionary. | ||
| /// </summary> | ||
| /// <param name="dict">A deserialized Json blob, received from the underlying model.</param> | ||
| public void FromDictionary(IDictionary<string, object> dict); | ||
| } | ||
|
|
||
| namespace Internal | ||
| { | ||
| // Internal class that contains logic for serialization and deserialization. | ||
| internal static class SerializationHelpers | ||
| { | ||
| // Given a serialized Json string, tries to convert it to the given type. | ||
| internal static object JsonStringToType(string jsonString, Type type) | ||
| { | ||
| var resultDict = Json.Deserialize(jsonString); | ||
| return ObjectToType(resultDict, type); | ||
| } | ||
|
|
||
| // Given an object received from the model, tries to convert it to the given type. | ||
| internal static object ObjectToType(object obj, Type type) | ||
| { | ||
| if (obj == null) return null; | ||
|
|
||
| // If the type is an interface, try to convert it to something we can handle. | ||
| if (type.IsInterface) | ||
| { | ||
| if (type.IsGenericType) | ||
| { | ||
| Type genericDef = type.GetGenericTypeDefinition(); | ||
| // Common interfaces to List<T> | ||
| if (genericDef == typeof(IEnumerable<>) || | ||
| genericDef == typeof(IList<>) || | ||
| genericDef == typeof(ICollection<>)) | ||
| { | ||
| type = typeof(List<>).MakeGenericType(type.GetGenericArguments()[0]); | ||
| } | ||
| else if (type == typeof(IList) || | ||
| type == typeof(IEnumerable)) | ||
| { | ||
| type = typeof(List<object>); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Convert the arg into the approriate type | ||
| if (obj is Type t) | ||
| { | ||
| return t; | ||
| } | ||
| else if (type.IsEnum) | ||
| { | ||
| if (obj is string str) return Enum.Parse(type, str); | ||
| return Enum.ToObject(type, obj); | ||
| } | ||
| else if (type.IsArray) | ||
| { | ||
| Type elementType = type.GetElementType(); | ||
| if (obj is not System.Collections.IList inputList) return null; | ||
|
|
||
| Array array = Array.CreateInstance(elementType, inputList.Count); | ||
| for (int i = 0; i < inputList.Count; i++) | ||
| { | ||
| array.SetValue(ObjectToType(inputList[i], elementType), i); | ||
| } | ||
| return array; | ||
| } | ||
| else if (type.IsGenericType && typeof(IList).IsAssignableFrom(type)) | ||
a-maurice marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| { | ||
| if (obj is not IList inputList) return null; | ||
|
|
||
| Type elementType = type.GetGenericArguments()[0]; | ||
|
|
||
| IList list = (IList)Activator.CreateInstance(type); | ||
|
|
||
| foreach (var input in inputList) | ||
| { | ||
| list.Add(ObjectToType(input, elementType)); | ||
| } | ||
| return list; | ||
| } | ||
| else if (obj is Dictionary<string, object> dict) | ||
| { | ||
| return DictionaryToType(dict, type); | ||
| } | ||
|
|
||
| try | ||
| { | ||
| return Convert.ChangeType(obj, type); | ||
| } | ||
| catch | ||
| { | ||
| return obj; | ||
| } | ||
| } | ||
|
|
||
| // Given a Json style dictionary, tries to convert it to the given type. | ||
| internal static object DictionaryToType(Dictionary<string, object> dict, Type type) | ||
| { | ||
| object item = Activator.CreateInstance(type); | ||
|
|
||
| // Check the class for the interface, and use that if available. | ||
| if (item is IFirebaseDeserializable deserializable) | ||
| { | ||
| deserializable.FromDictionary(dict); | ||
| return item; | ||
| } | ||
|
|
||
| // Otherwise, fall back to reflection, which will be slower. | ||
| BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase; | ||
| foreach (var kvp in dict) | ||
| { | ||
| try | ||
| { | ||
| // First, check for fields | ||
| FieldInfo field = type.GetField(kvp.Key, flags); | ||
| if (field != null) | ||
| { | ||
| field.SetValue(item, ObjectToType(kvp.Value, field.FieldType)); | ||
| continue; | ||
| } | ||
|
|
||
| // Otherwise, check for properties | ||
| PropertyInfo prop = type.GetProperty(kvp.Key, flags); | ||
| if (prop != null && prop.CanWrite) | ||
| { | ||
| prop.SetValue(item, ObjectToType(kvp.Value, prop.PropertyType)); | ||
| continue; | ||
| } | ||
| } | ||
| catch (Exception e) | ||
| { | ||
| UnityEngine.Debug.LogError($"Failed to convert object key {kvp.Key}, {e.Message}"); | ||
| } | ||
| } | ||
|
|
||
| return item; | ||
| } | ||
| } | ||
| } | ||
| } | ||
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.