Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 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# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI)

지난 글에서,

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

GitHub 이슈 데이터 정보를 벡터 변환 후 로컬 파일에 저장해 재사용을 했는데요, 사실 간단한 경우라면 몰라도 거의 이런 식으로 사용하는 경우는 없을 것입니다.

그보다는 DB를 활용하게 될 텐데요, 이번 글에서 소개하는 Qdrant가 바로 그런 벡터 데이터베이스 중의 하나입니다.

Qdrant
; https://youtu.be/xEFO1sQ2bUc?t=28371

그리고 .NET Conf 2023의 "Build Intelligent Apps with .NET and Azure" 동영상에서 이에 대한 사용법이 나옵니다. ^^ 역시 이번에도, 해당 강의 내용을 그대로 베껴 보겠습니다.




자, 그럼 지난 글에서 GitHub로부터 가져온 이슈 데이터를 Embedding 과정을 거쳐 벡터로 변환을 해 파일로 저장했는데요,

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

이번에는 Qdrant DB에 저장을 해보겠습니다. 이를 위해 docker로 qdrant 컨테이너를 하나 띄워 두시고,

docker run -p 6333:6333 -p 6334:6334 qdrant/qdrant

NuGet으로부터 Qdrant.Client를 참조 후 인스턴스를 생성합니다.

// Install-Package Azure.AI.OpenAI -Pre
// Install-Package Microsoft.DotNet.Interactive.AIUtilities -Pre
// Install-Package Qdrant.Client -Pre

string azureOpenAIKey = "...[azure openai key]..."; // 초기화 참고
string azureOpenAIEndpoint = "...[azure openai endpoint]...";
var embeddingDeployment = "my-embedding";

OpenAIClient openAIClient = new OpenAIClient(new System.Uri(azureOpenAIEndpoint), new AzureKeyCredential(azureOpenAIKey));

string qdrantHost = "localhost";
string collectionName = "github_issues";

QdrantClient qdrantClient = new QdrantClient(qdrantHost, 6334, false);

이후 동작은 지난 글에서 파일로 벡터 데이터를 저장했던 코드를 DB에 저장하게만 바꾸면 됩니다.

private static async Task EmbedAllIssuesAndSaveToDBAsync(
    QdrantClient qdrantClient, string collectionName, OpenAIClient openAIClient, string embeddingDeployment)
{
    GitHubIssue[]? issues = await LoadIssuesFromFileAsync("issues.json");
    if (issues == null)
    {
        Console.WriteLine("Failed to load issues.json");
        return;
    }

    var collections = await qdrantClient.ListCollectionsAsync();
    if (collections.Contains(collectionName))
    {
        // await qdrantClient.DeleteCollectionAsync(collectionName);
        return;
    }

    var issuesWithChunksColleciton =
        issues.Select(issue => new IssueWithChunks(issue, new()))
            .ToArray();

    var tokenizer = await Tokenizer.CreateAsync(TokenizerModel.ada2);

    foreach (var item in issuesWithChunksColleciton)
    {
        var fullText = item.Issue.Text;
        if (string.IsNullOrWhiteSpace(fullText))
        {
            continue;
        }

        var chunks = tokenizer.ChunkByTokenCountWithOverlap(fullText, 3000, 50)
            .Select(t =>
            $"""
            Title: {item.Issue.Title}

            {t}
            """).Chunk(16)
            .ToArray();

        foreach (var chunk in chunks)
        {
            var embeddingResponse = await openAIClient.GetEmbeddingsAsync(
                new EmbeddingsOptions(embeddingDeployment, chunk));

            item.Chunks.AddRange(
                embeddingResponse.Value.Data.Select(d =>
                new TextWithEmbedding(chunk[d.Index], d.Embedding.ToArray())));
        }
    }

    await qdrantClient.CreateCollectionAsync(collectionName,
        new VectorParams { Size = 1536, Distance = Distance.Cosine });

    var vectors = issuesWithChunksColleciton
        .Where(d => d.Chunks.Count > 0)
        .SelectMany(d =>
        d.Chunks.Select(c => new
        {
            Embedding = c.Embedding,
            Text = $"<issuesTitle>{d.Issue.Title}</issueTitle>\n<issueUrl>{d.Issue.Url}</issueUrl><issueContent>{d.Issue.Text}</issueContent>"
        }))
        .ToList();

    var points = vectors.Select(vector =>
    {
        var point = new PointStruct
        {
            Id = new PointId { Uuid = Guid.NewGuid().ToString() },
            Vectors = vector.Embedding,
            Payload =
            {
                ["text"] = vector.Text
            }
        };

        return point;
    }).ToList();

    await qdrantClient.UpsertAsync(collectionName, points);
}

이렇게 저장한 데이터를 다음과 같이 검색할 수 있습니다.

string question = "Are there any questions for mouse?";

string[] results = await SearchWithQdrantAsync(qdrantClient, collectionName,
    openAIClient, embeddingDeployment,
    question, 16);

results.All((text) =>
{
    Console.WriteLine(text);
    Console.WriteLine("-----------------------------------");
    return true;
});

Console.WriteLine($"Found: {results.Length}");

public static async Task<string[]> SearchWithQdrantAsync(
    QdrantClient qdrantClient, string collectionName,
    OpenAIClient openAIClient, string embeddingDeployment,
    string query, int resultLimit = 1)
{
    var embeddingResponse = await openAIClient.GetEmbeddingsAsync(
                    new EmbeddingsOptions(embeddingDeployment, new[] { query }));

    var embeddingVector = embeddingResponse.Value.Data[0].Embedding.ToArray();

    var results = await qdrantClient.SearchAsync(collectionName, embeddingVector, limit: (ulong)resultLimit);
    return results.Select(r => r.Payload["text"].StringValue).ToArray();
}

참고로, 이것 역시 자연어 검색을 하는 것은 아닙니다. DB를 생성하는 시점의 CreateCollectionAsync 코드를 보면 Distance를 Cosine 옵션으로 주고 있는 것을 볼 수 있는데요, 그러니까 이것도 역시 지난번에 설명한 유사도에 따른 검색에 해당합니다.

어쨌든, 이것으로 .NET Conf 2023에 있었던 "Build Intelligent Apps with .NET and Azure" 내용은 모두 정리했습니다. 해당 동영상의 마지막에는 다음과 같은 학습 자료를 공유하고 있으니 참고하세요. ^^

AI in .NET Collection
; https://aka.ms/ai-dotnet-learn
; https://learn.microsoft.com/en-us/collections/1n31t57k7k6r85

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




그나저나, OpenAI의 ChatGPT는 어떻게 해서 자연어 검색을 할 수 있는 걸까요? 아직 저도 완벽하게 이해하는 것은 아니지만, 대충 어떤 식일지는 짐작이 가는 듯합니다.

가령, 사용자가 질문을 하면, 그에 해당하는 키워드로 기존에 저장해 두었던 스토리지로부터 Vector 검색을 해 적당한 문서를 선별할 것입니다. 그런 다음, 그 문서를 "대화의 문맥"에 저장해 두고, 사용자의 질문을 그 문맥 내에서 다시 수행해 이후 적절한 문장으로 Completion 엔진을 통해 대답하는 식일 것입니다.

따라서, 우리가 가진 별도의 Knowledge base 자료가 있다면 그것을 Storage (VectorDB)에 저장한 후, 사용자가 질의를 하면 그것과 유사도가 높은 문서들을 VectorDB에서 검색한 다음 그 원본 문자열을 담은 문서를 다시 OpenAI API에 "질문"과 함께 전달해 ChatCompletion을 거치면 되는 식일 것입니다.




참고로, 왜 마이크로소프트는 OpenAI 서비스가 있는데, 그걸 굳이 Azure에 올려 Azure OpenAI로 따로 서비스를 하고 있는 걸까요? 사용자 입장에서 Azure OpenAI를 선택하면 어떤 장점이 있을지 궁금하지 않나요? ^^

지금까지의 코드를 보면, 질문뿐만 아니라 GitHub Issue 데이터를 Embedding하기 위해 OpenAI 측에 데이터를 전달해야만 했는데요, 사실 이런 과정이 보안을 중시하는 "기업" 입장에서는 매우 불편할 수가 있습니다. 실제로 얼마 전 삼성 전자가 사내에서 ChatGPT 사용을 금지한 이유가 그것 때문이었습니다.

'챗GPT 사내금지' 삼성전자, 직원업무 도울 자체 AI 도구 만든다
; https://www.yna.co.kr/view/AKR20230502125400003

이런 문제를 Azure OpenAI가 해결하는데요, 다음의 문서에서 이를 찾아볼 수 있습니다.

Data, privacy, and security for Azure OpenAI Service
; https://learn.microsoft.com/en-us/legal/cognitive-services/openai/data-privacy

Your prompts (inputs) and completions (outputs), your embeddings, and your training data:

are NOT available to other customers.
are NOT available to OpenAI.
are NOT used to improve OpenAI models.
are NOT used to improve any Microsoft or 3rd party products or services.
are NOT used for automatically improving Azure OpenAI models for your use in your resource (The models are stateless, unless you explicitly fine-tune models with your training data).
Your fine-tuned Azure OpenAI models are available exclusively for your use.


만약, Azure OpenAI의 비용이 부담스럽다면, 차선책으로 무료 LLM 모델인 LLaMA(라마)를 이용해 구축하는 방안이 있습니다.




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







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

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

비밀번호

댓글 작성자
 



2024-03-15 09시49분
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13608정성태4/26/2024417닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/2024415닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/2024431닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024676닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024700오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/2024875닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/2024938닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/2024966닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024975닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024936닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024979닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/2024973닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241079닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241069닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241083닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241090닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241226C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241201닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241083Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241158닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241275닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신 [2]파일 다운로드1
13587정성태3/27/20241361오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241534Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241497Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241457개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...