Using OpenAI API with C#
Introduction
This tutorial demonstrates how to integrate and use the OpenAI API with C# to leverage advanced AI capabilities in your applications.
1. Setting Up Your OpenAI API Key
Before starting, make sure you have your OpenAI API key ready. You can obtain it from the OpenAI website after signing up for an account.
2. Making API Requests
To make requests to the OpenAI API using C#, you'll typically use libraries like HttpClient or RestSharp. Here are examples of different API requests:
2.1 Text Completion Example
Example of completing text using the API:
using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; public class OpenAITextCompletionExample { private static readonly HttpClient client = new HttpClient(); static async Task Main() { string apiKey = "YOUR_API_KEY_HERE"; string prompt = "Translate English to French: Hello, how are you?"; string url = "https://api.openai.com/v1/completions"; HttpResponseMessage response = await client.PostAsync(url, new StringContent( $"{{\"prompt\":\"{prompt}\",\"max_tokens\":50}}", Encoding.UTF8, "application/json")); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } }
Output: Bonjour, comment vas-tu ?
2.2 Image Captioning Example
Example of generating a caption for an image:
using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; public class OpenAIImageCaptioningExample { private static readonly HttpClient client = new HttpClient(); static async Task Main() { string apiKey = "YOUR_API_KEY_HERE"; string imageUrl = "URL_TO_YOUR_IMAGE"; string url = "https://api.openai.com/v1/images/caption"; HttpResponseMessage response = await client.PostAsync(url, new StringContent( $"{{\"image\":\"{imageUrl}\"}}", Encoding.UTF8, "application/json")); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } }
Output: A dog running in the park.
3. Handling Responses
Once you receive a response from the API, you can handle it in your C# code. Here’s how you might handle the completion response:
// Assuming 'responseBody' contains the API response Console.WriteLine(responseBody);
In this example, responseBody
contains the JSON response from the OpenAI API.
Conclusion
Integrating the OpenAI API with C# allows you to enhance your applications with powerful AI capabilities. Explore more API endpoints and functionalities to innovate further.