Home > Mobile >  How to call ChatGPT from C# using HttpClientFactory, I keep getting errors and no responses
How to call ChatGPT from C# using HttpClientFactory, I keep getting errors and no responses

Time:01-30

Getting really irritated with this. The playground gives only python and node, trying to use this in C# and I keep getting errors. Here is how I have it setup.

First in the Program / Startup file, I am setting it up like so: (URL: https://api.openai.com/)

services.AddHttpClient("ChatGptAPI", client =>
{
    client.DefaultRequestHeaders.Clear();
    client.BaseAddress = aiOptions.Url;
    client.DefaultRequestHeaders.Add("Authorization", "Bearer "   aiOptions.Bearer);
});

Then in my method, I am calling this:

            var client = _httpFactory.CreateClient("ChatGptAPI");
            var payload = new
            {
                prompt = $"Create a first person story\n\n{storyText}",
                temperature = "0.5",
                max_tokens = "1500",
                model = "text-davinci-003"
            };

            var content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
            var response = await client.PostAsync("v1/completions", content);

            Console.WriteLine("ChatGptAPI result:");
            Console.WriteLine(response.RequestMessage);

I at first I kept getting Bad Request errors, but once I tried other URLs for the request, it appears to go through, but the response is blank.

For the life of me, I cannot find any samples out there that has C# calling these services.

Any help would be great.

I have tried multiple URLs, I've tried running this in Playground and view code and I've searched for other samples, but this keeps failing or returning nothing. Also tried using the OpenAI Nuget package, that was a waste of time.

CodePudding user response:

If you are actually managing to reach the completions endpoint and you have a valid key then you are just reading the wrong object back.

After you get your response you should read it, something like:

var gptResponse = await response.Content.ReadAsStringAsync();

you can then parse or better deserialize the API response

  • Related