Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [링크 복사], [링크+제목 복사],
조회: 6549
글쓴 사람
정성태 (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)
13437정성태11/8/20232829닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20233079닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20232988닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232768스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232469스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232546오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232908스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232746닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20233027닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233116닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233308닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233465스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233244닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233218스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233370닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233452닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235721스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233284스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233984닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233515닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233298오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233799닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233567디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233758닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20237060닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233551Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...