Код для доступа к API на разных языках программирования



Через POST-запрос

С# (async)


Пример прислан одним из наших пользователей

static async Task Main()
        {

            string apiKey = "sk-or-vv-86*************"; // ваш ключ в VseGPT после регистрации
            string baseApiUrl = "https://api.vsegpt.ru/v1/";
            string prompt = "Напиши последовательно числа от 1 до 10";

            try
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");

                List<dynamic> messages = new List<dynamic>();
                messages.Add(new { role = "user", content = prompt });

                var requestData = new
                {
                    model = "anthropic/claude-instant-v1",
                    messages = messages,
                    temperature = 0.7,
                    n = 1,
                    max_tokens = Convert.ToInt32(prompt.Length * 1.5),
                    extra_headers = new { X_Title = "My App" } // опционально - передача информации об источнике API-вызова
                };

                var jsonRequest = Newtonsoft.Json.JsonConvert.SerializeObject(requestData);
                var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(baseApiUrl + "chat/completions", content);

                if (response.IsSuccessStatusCode)
                {
                    var jsonResponse = await response.Content.ReadAsStringAsync();
                    dynamic responseData = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonResponse);
                    string responseContent = responseData.choices[0].message.content;
                    Console.WriteLine("Response: " + responseContent);
                }
                else
                {
                    Console.WriteLine("Error: " + response.ReasonPhrase);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
            }
}

TypeScript

fetch("https://api.vsegpt.ru:6070/v1/chat/completions", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${VSEGPT_API_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    "model": "openai/gpt-3.5-turbo",
    "messages": [
      {"role": "user", "content": "What is the meaning of life?"}
    ]
  })
});


Python

import requests
import json

response = requests.post(
  url="https://api.vsegpt.ru:6070/v1/chat/completions",
  headers={
    "Authorization": f"Bearer {VSEGPT_API_KEY}"
  },
  data=json.dumps({
    "model": "openai/gpt-3.5-turbo", 
    "messages": [
      {"role": "user", "content": "What is the meaning of life?"}
    ]
  })
)
print(response.text)

Shell (CURL)

curl https://api.vsegpt.ru:6070/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $VSEGPT_API_KEY" \
  -d '{
  "model": "openai/gpt-3.5-turbo", 
  "messages": [
    {"role": "user", "content": "What is the meaning of life?"}
  ]
}'

Через библиотеки

TypeScript

import OpenAI from "openai"

const openai = new OpenAI({
  baseURL: "https://api.vsegpt.ru:6070/v1",
  apiKey: $VSEGPT_API_KEY,
  // dangerouslyAllowBrowser: true,
})
async function main() {
  const completion = await openai.chat.completions.create({
    model: "openai/gpt-3.5-turbo",
    messages: [
      { role: "user", content: "Say this is a test" }
    ],
  })

  console.log(completion.choices[0].message)
}
main()

Библиотеки для других языков


Должно подходить большинство библиотек для других языков программирования. Например, их можно взять здесь: https://platform.openai.com/docs/libraries/community-libraries