Search code examples
c#asp.net-coreopenai-apichat-gpt-4

Using ChatGPT4 Vision in ASP.NET Core


I am working on a web application with openai integration. I have the standard chat prompt and response implemented, but I am having issues accessing the vision api. All of the examples I can find are in python. I whipped up quick Jupyter Notebook and called the vision model with my api key and it worked great. Looking for a way to translate this code into C# or a viable solution to use the code in my application.

from openai import OpenAI

client = OpenAI(api_key="___")

response = client.chat.completions.create(
    model="gpt-4-vision-preview",
    messages=[
    {
      "role": "user",
      "content": [
        {"type": "text", "text": "Does this image show a Fender Stratocaster Electric Guitar?        Respond with yes or no."},
        {
          "type": "image_url",
          "image_url": {
            "url": "https://toneshapers.com/cdn/shop/files/Les-Paul-Standard-Front.jpg",
          },
        },
      ],
    }
  ],
  max_tokens=300,
)

print(response.choices[0])

I have tried to access "chat.completions" from my openai instance in C#, but they do not seem to exist.


Solution

  • The documentation includes a cURL sample which can easily be translated to a C# HttpRequest:

    curl https://api.openai.com/v1/chat/completions \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $OPENAI_API_KEY" \
      -d '{
        "model": "gpt-4-vision-preview",
        "messages": [
          {
            "role": "user",
            "content": [
              {
                "type": "text",
                "text": "What’s in this image?"
              },
              {
                "type": "image_url",
                "image_url": {
                  "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
                }
              }
            ]
          }
        ],
        "max_tokens": 300
      }'