Collaboration-2-Go


Lösungen und Software-Entwicklung im Collaboration Umfeld, insbesondere Microsoft SharePoint, Microsoft Exchange und Microsoft Office.

Support


Mobil: +49 (152) 53 97 78 79
Mail: service@collaboration-2-go.de
Weitere Kontaktmöglichkeiten: Kontaktseite
Dekoration: Köln



Query OpenAI's ChatGPT
Created: 18.01.2023
Categories: Open AI


Query OpenAI's ChatGPT and get an answer by sending a completion request.

Very simple example:


// add using
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Text.Json;
...

// add necessary variables
string endpoint = "https://api.openai.com/v1/engines/{model}/completions";
// model:
// text-davinci-003: data until Jun 2021, most capable model
// text-curie-001: data until Oct 2019, very capable model
// text-babbage-001: data until Oct 2019, capable of straightforward tasks
// text-ada-001: data until Oct 2019, capable of very simple tasks
// Note: request changes with the model, this sample uses text-davinci-003
string model = "text-davinci-003";
string key = "get_your_own"; // https://beta.openai.com/account/api-keys
int temp = 0;
int maxTokens = 2048;
string question = "What is ChatGPT?";
string answer;

// add function call
try
{
    answer = queryOpenAI(question, endpoint, model, key, temp, maxTokens);
}
catch (Exception ex)
{
    // your error handling
}

...

// query function
public string queryOpenAI(string question, string endpoint, string model, string key, int temp, int maxTokens)
{
    System.Net.ServicePointManager.SecurityProtocol =
        System.Net.SecurityProtocolType.Tls12 |
        System.Net.SecurityProtocolType.Tls11 |
        System.Net.SecurityProtocolType.Tls;

    // build request
    string endpointUrl = endpoint.Replace("{model}", model);
    var request = WebRequest.Create(endpointUrl);
    request.Method = "POST";
    request.ContentType = "application/json";
    request.Headers.Add("content-type", "application/json");
    request.Headers.Add("Authorization", "Bearer " + key);

    //  create data for request
    var sb = new StringBuilder();
    sb.Append("{");
    sb.Append(" \"model\":\"" + model + "\",");
    sb.Append(" \"prompt\": \"" + encodeQuotes(question) + "\",");
    sb.Append(" \"max_tokens\": " + maxTokens + ",");
    sb.Append(" \"temperature\": " + temp);
    sb.Append("}");
    string data = sb.ToString();

    // send request
    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(data);
        streamWriter.Flush();
        streamWriter.Close();
    }

    // get response
    var response = request.GetResponse();
    var streamReader = new StreamReader(response.GetResponseStream());
    string json = streamReader.ReadToEnd();
    var oair = JsonSerializer.Deserialize(json);

    // return result
    return oair.choices[0].text;
}

// get quotes
private string encodeQuotes(string s)
{
    if (s.IndexOf("\\") != -1)
        s = s.Replace("\\", @"\\");

    if (s.IndexOf("\n\r") != -1)
        s = s.Replace("\n\r", @"\n");

    if (s.IndexOf("\r") != -1)
        s = s.Replace("\r", @"\r");

    if (s.IndexOf("\n") != -1)
        s = s.Replace("\n", @"\n");

    if (s.IndexOf("\t") != -1)
        s = s.Replace("\t", @"\t");

    if (s.IndexOf("\"") != -1)
        return s.Replace("\"", @"""");
    else
        return s;
}

// Helper classes generated by https://json2csharp.com/
public class OpenAIResponse
{
    public string id { get; set; }
    public string @object { get; set; }
    public int created { get; set; }
    public string model { get; set; }
    public List choices { get; set; }
    public Usage usage { get; set; }
}

public class Choice
{
    public string text { get; set; }
    public int index { get; set; }
    public object logprobs { get; set; }
    public string finish_reason { get; set; }
}

public class Usage
{
    public int prompt_tokens { get; set; }
    public int completion_tokens { get; set; }
    public int total_tokens { get; set; }
}


Further Reading:
- API Reference
- Keys / Registration
- Models
- Tokens
- JSON - C# Class Generator


    

Send us a Comment!