Error while compile project in C# with Async method

Hello everyone,

I am trying to use the GPT-4 Vision API but need to run the code synchronously instead of asynchronously.

Here is the code I tried. It works in my tests, but due to the use of the ? syntax in the last line to get the response, it requires Microsoft.CSharp, which is not compatible with .NET Framework 4.6.2.

To work around this, I removed the ? syntax, but now, when I try to access responseData, I always get the following error:

Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create

Unfortunately, running the code asynchronously is not an option as it needs to be executed in a plugin that does not support async code.

Does anyone know how to handle this issue or have any suggestions on how to make this work synchronously without running into compatibility problems?

Thank you!

private string GetKeyValuePairsViaOpenAiVision(string payload)
{
   string JSONContent = "";
   var httpClient = Ctx.Azure.HttpClientWithHeaders; // Get the HttpClient instance from Azure class

   var content = new StringContent(payload, Encoding.UTF8, "application/json");
   var response = httpClient.PostAsync(Ctx.Azure.OpenAiVisionEndpoint, content).GetAwaiter().GetResult(); // Use .Result to run synchronously

   if (response.IsSuccessStatusCode)
   {
       var responseData = JsonConvert.DeserializeObject<dynamic>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
       JSONContent = responseData?.choices[0]?.message?.content;
   }

   return JSONContent;
}

Why not use .Net 8 instead of 4.6.2?

Becasue this code is used for plugin in Power Apps.

And the only one that can be used is .NET 462.

The above problem solved that way…

  • I removed the Microsoft.CSharp package from my project.

  • I added three properties in the class, OpenAIVisionRepsonse, Choice and Message.

public class OpenAiVisionResponse
{
    public Choice[] Choices { get; set; }
}

public class Choice
{
    public Message Message { get; set; }
}

public class Message
{
    public string Content { get; set; }
}
  • And finally I modified the GetKeyValuePairsViaOpenAiVision() like below:
if (response.IsSuccessStatusCode)
{
    var responseData = JsonConvert.DeserializeObject<OpenAiVisionResponse>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
    
    if (responseData != null && responseData.Choices != null && responseData.Choices.Length > 0)
    {
        JSONContent = responseData.Choices[0].Message.Content;
    }
}
1 Like