Skip to content
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

Providers: Added ability to get typed object from ChatResponse #247

Open
HavenDV opened this issue Apr 23, 2024 · 0 comments
Open

Providers: Added ability to get typed object from ChatResponse #247

HavenDV opened this issue Apr 23, 2024 · 0 comments

Comments

@HavenDV
Copy link
Contributor

HavenDV commented Apr 23, 2024

public async Task<T> Ask<T>(string prompt)
{
    string jsonStructure = Utils.GenerateJsonStructure<T>();
    string expandedPrompt = $"{prompt}\nPlease provide the response in the following json format: {jsonStructure}";
    var response = await Ask(expandedPrompt);

    //sometimes gemini add some weird stuff around the json
    if (response.StartsWith("```json"))
    {
        response = response.Substring(7);
        response = response.Substring(0, response.Length - 4);
    }
    
    try
    {
        return JsonSerializer.Deserialize<T>(response);
    }
    catch (Exception e)
    {
        throw new Exception("Failed to generate a valid response from the Gemini API.");
    }
}

public static string GenerateJsonStructure<T>()
{
    var properties = typeof(T).GetProperties();
    var jsonStructure = new StringBuilder();
    jsonStructure.AppendLine("{");

    foreach (var property in properties)
    {
        jsonStructure.AppendLine($"  \"{property.Name}\": \"{property.PropertyType.Name}\",");
    }

    jsonStructure.Remove(jsonStructure.Length - 3, 1); // Remove the trailing comma
    jsonStructure.AppendLine("}");

    return jsonStructure.ToString();
}

that version is pretty brittle

looks like this is using gemeni directly for the large context

but no longer is working at it refuses to return pure json without commentary

3:28
OpenAI can be asked to return the response in json format.
But in general, of course, I like your approach, I could implement this as an Extension to ChatResponse, which casts the message object to a strict type.
Something like ChatResponse.As()

But need to test this with different providers, some may ignore formatting/requests to output or output it without ```json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant