Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [링크 복사], [링크+제목 복사]
조회: 6322
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 3개 있습니다.)
(시리즈 글이 6개 있습니다.)
.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록
; https://www.sysnet.pe.kr/2/0/13344

닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작
; https://www.sysnet.pe.kr/2/0/13451

닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법
; https://www.sysnet.pe.kr/2/0/13452

닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI)
; https://www.sysnet.pe.kr/2/0/13454

닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용
; https://www.sysnet.pe.kr/2/0/13455

닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성
; https://www.sysnet.pe.kr/2/0/13456




C# - OpenAI API 사용 - 지원 모델 목록

소소하게 OpenAI에 대해 알아보려고 합니다. ^^

우선, 당연히 API Key를 구해야 하는데요, 이것은 OpenAI 가입 후 "https://platform.openai.com/account/api-keys" 경로에서 생성할 수 있습니다.

openai_models_1.png

저게 끝입니다. ^^ 이후로는 API Reference 문서를 보며,

API REFERENCE
; https://platform.openai.com/docs/api-reference/introduction

코딩을 하면 되는데요, 이번 글에서는 단순히 OpenAI가 지원하는 Model에 대해서만 구해보겠습니다. 이를 위해 curl을 이용할 수 있으며, 문서에 보면 다음과 같이 전송하면 된다고 나옵니다.

curl https://api.openai.com/v1/models \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "OpenAI-Organization: org-UhFLodPvMdmkbjhIFFSgPr7n"

위의 내용에서 OPENAI_API_KEY는 방금 전 생성한 Key이고, OpenAI-Organization은 별도로 "Settings" 메뉴에서 구할 수 있는데요,

openai_models_2.png

"Personal"에 대해서는 동일하게 예제와 같은 "org-UhFLodPvMdmkbjhIFFSgPr7n" 값이기 때문에 그대로 복사해도 됩니다.

curl https://api.openai.com/v1/models -H "Authorization: Bearer ...your_key..." -H "OpenAI-Organization: org-UhFLodPvMdmkbjhIFFSgPr7n"

기본적으로 Personal의 경우 "OpenAI-Organization" 값을 생략해도 API 호출은 잘 동작합니다. 따라서 아래와 같이 수행할 수 있는데요,

C:\temp> curl https://api.openai.com/v1/models -H "Authorization: Bearer sk-YQ...[생략]...Ms8"
{
  "object": "list",
  "data": [
    {
      "id": "babbage",
      "object": "model",
      "created": 1649358449,
      "owned_by": "openai",
      "permission": [
        {
          "id": "modelperm-49FUp5v084tBB49tC4z8LPH5",
          "object": "model_permission",
          "created": 1669085501,
          "allow_create_engine": false,
          "allow_sampling": true,
          "allow_logprobs": true,
          "allow_search_indices": false,
          "allow_view": true,
          "allow_fine_tuning": false,
          "organization": "*",
          "group": null,
          "is_blocking": false
        }
      ],
      "root": "babbage",
      "parent": null
    },

    ...[생략]...

    {
      "id": "text-babbage:001",
      "object": "model",
      "created": 1642018370,
      "owned_by": "openai",
      "permission": [
        {
          "id": "snapperm-7oP3WFr9x7qf5xb3eZrVABAH",
          "object": "model_permission",
          "created": 1642018480,
          "allow_create_engine": false,
          "allow_sampling": true,
          "allow_logprobs": true,
          "allow_search_indices": false,
          "allow_view": true,
          "allow_fine_tuning": false,
          "organization": "*",
          "group": null,
          "is_blocking": false
        }
      ],
      "root": "text-babbage:001",
      "parent": null
    }
  ]
}

위에서 출력된 값은 https://api.openai.com/v1/models로 질의를 했기 때문에 OpenAI가 지원하는 다양한 AI Model에 해당합니다. C#으로는 기왕이면 ^^ 인텔리센스의 도움을 받을 수 있도록 대략 다음과 같이 코딩하면 좋을 것입니다.

using OpenAI;
using System.Net.Http.Json;
using System.Text.Json.Serialization;

internal class Program
{
    static HttpClient _httpClient = new HttpClient();

    private static async Task Main(string[] args)
    {
        string modelUrl = "https://api.openai.com/v1/models";

        ModelList? models =  await _httpClient.GetFromJsonAsync<ModelList>(modelUrl, SourceGenerationContext.Default.ModelList);
        if (models == null)
        {
            return;
        }

        foreach (Model model in models.Data)
        {
            Console.WriteLine($"{model.Id}");
        }
    }

    static Program()
    {
        (string apiKey, string orgName) = GetKeyInfo(@"d:\settings\openai_key.txt");

        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
        if (string.IsNullOrEmpty(orgName) == false)
        {
            _httpClient.DefaultRequestHeaders.Add("OpenAI-Organization", orgName);
        }
    }

    private static (string apiKey, string orgName) GetKeyInfo(string filePath)
    {
        string[] keyInfo = File.ReadLines(filePath).ToArray();
        return (keyInfo[0], (keyInfo.Length > 1) ? keyInfo[1] : "");
    }
}

namespace OpenAI
{
#if DEBUG
    [JsonSourceGenerationOptions(WriteIndented = true)]
#endif
    [JsonSerializable(typeof(ModelList))]
    [JsonSerializable(typeof(Model))]
    [JsonSerializable(typeof(Permission))]
    internal partial class SourceGenerationContext : JsonSerializerContext // .NET 6부터 SourceGenerator와 통합된 System.Text.Json
    {
    }

    public class ModelList
    {
        [JsonPropertyName("object")]
        public string Object { get; set; } = "";

        [JsonPropertyName("data")]
        public List<Model> Data { get; set; } = new List<Model>(); // System.Text.Json의 역직렬화 시 필드/속성 주의

        public override string ToString()
        {
            return $"{Object}: # of data: {Data.Count}";
        }
    }

    public class Model
    {
        [JsonPropertyName("id")]
        public string Id { get; set; } = "";

        [JsonPropertyName("object")]
        public string Object { get; set; } = "";

        [JsonPropertyName("created")]
        public int Created { get; set; }

        [JsonPropertyName("owned_by")]
        public string OwnedBy { get; set; } = "";

        [JsonPropertyName("permission")]
        public List<Permission> Permissions { get; set; } = new List<Permission>();

        [JsonPropertyName("root")]
        public string Root { get; set; } = "";

        [JsonPropertyName("parent")]
        public string Parent { get; set; } = "";

        public override string ToString()
        {
            return $"{Id}, # of permissions: {Permissions.Count}";
        }
    }

    public class Permission
    {
        [JsonPropertyName("id")]
        public string Id { get; set; } = "";

        [JsonPropertyName("object")]
        public string Object { get; set; } = "";

        [JsonPropertyName("created")]
        public int Created { get; set; }

        [JsonPropertyName("allow_create_engine")]
        public bool AllowCreateEngine { get; set; }

        [JsonPropertyName("allow_sampling")]
        public bool AllowSampling { get; set; }

        [JsonPropertyName("allow_logprobs")]
        public bool AllowLogprobs { get; set; }

        [JsonPropertyName("allow_search_indices")]
        public bool AllowSearchIndices { get; set; }

        [JsonPropertyName("allow_view")]
        public bool AllowView { get; set; }

        [JsonPropertyName("allow_fine_tuning")]
        public bool AllowFineTuning { get; set; }

        [JsonPropertyName("organization")]
        public string Organization { get; set; } = "";

        [JsonPropertyName("group")]
        public string Group { get; set; } = "";

        [JsonPropertyName("is_blocking")]
        public bool IsBlocking { get; set; }

        public override string ToString()
        {
            return $"{Id}, {Object}";
        }
    }
}

출력 결과는 2023-05-08 기준으로 다음과 같습니다.

babbage
davinci
text-davinci-edit-001
babbage-code-search-code
text-similarity-babbage-001
code-davinci-edit-001
text-davinci-001
ada
babbage-code-search-text
babbage-similarity
code-search-babbage-text-001
text-curie-001
code-search-babbage-code-001
text-ada-001
text-embedding-ada-002
text-similarity-ada-001
curie-instruct-beta
ada-code-search-code
ada-similarity
code-search-ada-text-001
text-search-ada-query-001
davinci-search-document
ada-code-search-text
text-search-ada-doc-001
davinci-instruct-beta
gpt-3.5-turbo
text-similarity-curie-001
code-search-ada-code-001
ada-search-query
text-search-davinci-query-001
curie-search-query
gpt-3.5-turbo-0301
davinci-search-query
babbage-search-document
ada-search-document
text-search-curie-query-001
whisper-1
text-search-babbage-doc-001
curie-search-document
text-davinci-003
text-search-curie-doc-001
babbage-search-query
text-babbage-001
text-search-davinci-doc-001
text-search-babbage-query-001
curie-similarity
curie
text-similarity-davinci-001
text-davinci-002
davinci-similarity
cushman:2020-05-03
ada:2020-05-03
babbage:2020-05-03
curie:2020-05-03
davinci:2020-05-03
if-davinci-v2
if-curie-v2
if-davinci:3.0.0
davinci-if:3.0.0
davinci-instruct-beta:2.0.0
text-ada:001
text-davinci:001
text-curie:001
text-babbage:001

각각의 특징에 대해서는 다음의 글을 참고하시면 도움이 될 것입니다. ^^

OpenAI API 모델 7가지는 알고 갑시다
; https://iotnbigdata.tistory.com/609

부가적으로, 위의 모델들에 대한 종류를 "Rate limits"에서 확인할 수 있습니다. ^^

openai_models_4.png

재미있는 건, ChatGPT 사이트에서는 "GPT-3.5" 기본값에 "GPT-4"도 사용할 수 있지만 API로는 아직 제공하지 않고 있습니다. 어쨌든 대충 API로 제공되는 Model을 정리하면,

Chat - gpt-3.5-turbo, gpt-3.5-turbo-0301
Moderation - text-moderation-latest, text-moderation-stable
Image - DALL·E 2
Audio - whisper-1
나머지 전부 - Text

이렇게 간단하게 나뉩니다. 오히려 이걸 /v1/models API로 반환한 값으로는 딱히 분류할 기준이 마땅치 않습니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




참고로, OpenAI API는 무료로 $18 용량이 주어지고, 이후로는 과금을 해야 합니다. 과금은 "Billing" 메뉴에서 신청할 수 있고 월 정액이 아닌, 쓴 만큼 내는 구조인데 최대 설정의 기본값이 $120입니다. (실수로 엄청난 과금 폭탄을 맞지 않을 수 있습니다. ^^)

이에 대해서는 Usage 메뉴에 다음과 같은 표로 쉽게 확인할 수 있습니다.

openai_models_3.png

위의 과금 신청과 ChatGPT의 월 정액 $20 과금은 완전히 별개입니다. (즉, 따로 신청해야 합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/24/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2023-11-17 08시32분
This is a simple app that converts a screenshot to HTML/Tailwind CSS. It uses GPT-4 Vision to generate the code, and DALL-E 3 to generate similar looking images.
; https://github.com/abi/screenshot-to-code
; https://twitter.com/DevDminGod/status/1725175630029803538
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13600정성태4/18/2024204닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024259닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024269닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024334닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024654닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024779닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/2024983닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241043닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241202C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241162닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241071Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241138닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241191닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241147오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241290Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241092Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241046개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241148Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241221Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241585개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241136닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241493오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241626닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241864닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...