Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [링크 복사], [링크+제목 복사],
조회: 6539
글쓴 사람
정성태 (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)
13283정성태3/12/20233644오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/20233967Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/20233923Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
13280정성태3/9/20234696개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
13279정성태3/9/20234209오류 유형: 851. 파이썬 ModuleNotFoundError: No module named '_cffi_backend'
13278정성태3/8/20234190개발 환경 구성: 669. WSL 2의 (init이 아닌) systemd 지원 [1]
13277정성태3/6/20234827개발 환경 구성: 668. 코드 사인용 인증서 신청 및 적용 방법(예: Digicert)
13276정성태3/5/20234507.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
13275정성태3/3/20234809.NET Framework: 2101. C# 11의 ref 필드 설명
13274정성태3/2/20234367.NET Framework: 2100. C# - ref 필드로 ref struct 타입을 허용하지 않는 이유
13273정성태2/28/20234129.NET Framework: 2099. C# - 관리 포인터로서의 ref 예약어 의미
13272정성태2/27/20234369오류 유형: 850. SSMS - mdf 파일을 Attach 시킬 때 Operating system error 5: "5(Access is denied.)" 에러
13271정성태2/25/20234334오류 유형: 849. Sql Server Configuration Manager가 시작 메뉴에 없는 경우
13270정성태2/24/20233897.NET Framework: 2098. dotnet build에 /p 옵션을 적용 시 유의점
13269정성태2/23/20234505스크립트: 46. 파이썬 - uvicorn의 콘솔 출력을 UDP로 전송
13268정성태2/22/20235043개발 환경 구성: 667. WSL 2 내부에서 열고 있는 UDP 서버를 호스트 측에서 접속하는 방법
13267정성태2/21/20234943.NET Framework: 2097. C# - 비동기 소켓 사용 시 메모리 해제가 finalizer 단계에서 발생하는 사례파일 다운로드1
13266정성태2/20/20234559오류 유형: 848. .NET Core/5+ - Process terminated. Couldn't find a valid ICU package installed on the system
13265정성태2/18/20234484.NET Framework: 2096. .NET Core/5+ - PublishSingleFile 유형에 대한 runtimeconfig.json 설정
13264정성태2/17/20236020스크립트: 45. 파이썬 - uvicorn 사용자 정의 Logger 작성
13263정성태2/16/20234164개발 환경 구성: 666. 최신 버전의 ilasm.exe/ildasm.exe 사용하는 방법
13262정성태2/15/20235223디버깅 기술: 191. dnSpy를 이용한 (소스 코드가 없는) 닷넷 응용 프로그램 디버깅 방법 [1]
13261정성태2/15/20234506Windows: 224. Visual Studio - 영문 폰트가 Fullwidth Latin Character로 바뀌는 문제
13260정성태2/14/20234308오류 유형: 847. ilasm.exe 컴파일 오류 - error : syntax error at token '-' in ... -inf
13259정성태2/14/20234466.NET Framework: 2095. C# - .NET5부터 도입된 CollectionsMarshal
13258정성태2/13/20234309오류 유형: 846. .NET Framework 4.8 Developer Pack 설치 실패 - 0x81f40001
1  2  3  4  5  6  7  8  9  10  11  12  13  [14]  15  ...