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# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법

ChatGPT에 들어가,

ChatGPT
; https://chat.openai.com/

정보를 요청하는 대화를 시작하는 경우, 그 정보의 소스는 사실 대부분 웹 페이지 등에 공개된 것입니다. (게다가, 그 정보를 정리한 시점은 2023-11-22일 기준으로 2022년 1월이라고 합니다.)

이것을 다시 말하면, 사내에 구축된 Knowledge Base 시스템에 있는 정보들은 ChatGPT 입장에서 절대로 알 수 없습니다. 그렇다면, 그런 데이터를 대상으로 질의 시스템을 만들고 싶다면 어떻게 해야 할까요?

이에 대한 답변 역시, ^^ .NET Conf 2023에서 다 나온 내용입니다. 이름하여 "Embedding Search"라고 하는데요,

Build Intelligent Apps with .NET and Azure - Embedding Search
; https://youtu.be/xEFO1sQ2bUc?t=27934

정리하는 차원에서 그대로 베껴 보겠습니다. ^^




자, 그럼 먼저 적당한 데이터 예제를 구해야 하는데요, "Build Intelligent Apps with .NET and Azure - Embedding Search" 글에서도 예를 들었던 GitHub 이슈를 저도 다뤄보겠습니다. 하지만, 이에 대해서는 저번에 별도의 글로 설명했으니,

C# - Octokit을 이용한 GitHub Issue 검색
; https://www.sysnet.pe.kr/2/0/13450

위의 예제를 돌리면 (여러분의 GitHub Repo를 대상으로 해도 됩니다.) 대략 다음과 같은 식의 issues.json 파일을 구할 수 있을 것입니다.

[
  {
    "Title": "Increase hold of left click",
    "Text": "Hello, thank you for making this project open source. I ran succefully in a raspberry pi zero w. However, I need to hold the left click for around 3-4 seconds. Could you please give a general instruction on how I can achieve this?\r\n\r\nI was trying to add a sleep at the end of MouseDevice::SendRelative function inside the rasp_vusb_server but I\u0027m having some trouble building this project. Could you please inform If I\u0027m in the right path.",
    "Url": "https://github.com/stjeong/rasp_vusb/issues/16"
  },

  // ...[생략]...
]

그렇다면 우선 저 데이터를 로딩해야겠군요. ^^

GitHubIssue[]? issues = await LoadIssuesFromFileAsync("issues.json");
if (issues == null)
{
    Console.WriteLine("Failed to load issues.json");
    return;
}

public static async Task<GitHubIssue[]?> LoadIssuesFromFileAsync(string fileName)
{
    var filePath = Path.Combine("..", "..", "..", fileName);
    var text = await File.ReadAllTextAsync(filePath);
    return JsonSerializer.Deserialize<GitHubIssue[]>(text);
}

public record GitHubIssue(string Title, string Text, string Url);

이렇게 로딩한 데이터는 단순히 "텍스트" 문자열을 담고 있기 때문에 (단순한 비교를 넘는) 검색을 할 수 없습니다. 즉, 사람이 이해하는 형식의 문자열을 수학으로 이해할 수 있는 형식의 연산 가능한 숫자로 바꿔야 하는데요, 간단하게 말하면 문자열을 숫자 벡터로 바꿔주는 Embedding 과정을 거쳐야 하는 것입니다.

Azure OpenAI로부터 Embedding을 하려면 지난 글에 설명한 것과 같은 방식으로, 즉 Azure Portal의 "Model deployments"로 들어가 "배포"에서 Embedding을 위한 모델을 하나 만들어야 합니다.

open_ai_embed_1.png

New and improved embedding model
; https://openai.com/blog/new-and-improved-embedding-model

이렇게 생성한 Embedding 모델을 이용해 이제 GitHub 이슈의 텍스트 정보를 벡터로 변환해 줍니다.

// NuGet 참조 추가
// Install-Package Azure.AI.OpenAI -Pre
// Install-Package Microsoft.DotNet.Interactive.AIUtilities -Pre
// Install-Package System.Numerics.Tensors

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

GitHubIssue[]? issues = await LoadIssuesFromFileAsync("issues.json");
if (issues == null)
{
    Console.WriteLine("Failed to load issues.json");
    return;
}

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

Console.WriteLine(issuesWithChunksColleciton);

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 SaveIssuesWithChunksToFileAsync(issuesWithChunksColleciton, "issueWithEmbeddingsSubset.json");

public static async Task SaveIssuesWithChunksToFileAsync(IEnumerable<IssueWithChunks> data, string fileName)
{
    var filePath = Path.Combine("..", "..", "..", fileName);
    var issuesJson = JsonSerializer.Serialize(data, new JsonSerializerOptions(
        JsonSerializerOptions.Default)
    { WriteIndented = true });
    await File.WriteAllTextAsync(filePath, issuesJson);
}

public record TextWithEmbedding(string Text, float[] Embedding);
public record IssueWithChunks(GitHubIssue Issue, List<TextWithEmbedding> Chunks);

매번 동일한 데이터에 GetEmbeddingsAsync를 호출하면 OpenAI API 사용량만 늘려 비용을 발생시키므로 위의 예제에서는 그 결과를 "issueWithEmbeddingsSubset.json" 파일에 보관하고 있습니다.

이렇게 한번 Embedding 데이터를 구축했으면 이후에는 그 벡터를 활용해 검색하면 되는데요, (벡터 검색만으로는 충분한가?) 하지만 검색을 위한 문자열도 동일한 Embedding 모델로 벡터 변환을 한 후 검색하는 식으로 코딩을 하면 됩니다.

var embeddingDeployment = "my-embedding"; // Azure AI Studio에서 생성한 배포 이름

OpenAIClient openAIClient = // ...[초기화 코드 생략]...

var issuesWithChunksCollection = await LoadIssuesWithChunksFromFileAsync("issueWithEmbeddingsSubset.json");

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

string[] results = await EmbeddingSearchAsync(openAIClient, embeddingDeployment, 
    question, issuesWithChunksCollection!, issuesWithChunksCollection.Length);

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

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

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

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

    var searchResults = 
        data
        .SelectMany(d => d.Chunks)
        .ScoreBySimilarityTo(embeddingVector, new SimilarityComparer(), c => c.Embedding)
        .OrderByDescending(e => e.Value)
        .Where(e => e.Value > 0.5)
        .Take(resultLimit)
        .Select(e => e.Key.Text)
        .ToArray();

    return searchResults;
}

public static async Task<IssueWithChunks[]?> LoadIssuesWithChunksFromFileAsync(string fileName)
{
    var filePath = Path.Combine("..", "..", "..", fileName);
    var text = await File.ReadAllTextAsync(filePath);
    return JsonSerializer.Deserialize<IssueWithChunks[]>(text);
}

public class SimilarityComparer : ISimilarityComparer
{
    public float Score(float[] a, float[] b)
    {
        return TensorPrimitives.CosineSimilarity(a, b);
    }
}

위의 코드에서는 "Are there any issues for mouse?"라는 질문을 던져 issueWithEmbeddingsSubset.json에 있던 벡터들과 CosineSimilarity를 비교해 연관이 높은 이슈를 반환하는데요, 결과를 보면 16개의 이슈 중 12개를 반환하고 있습니다.

Title: Mouse movement not working with Linux Systems

Hello!

A represent a team of engineers that are enjoying using your application to automate mouse and keyboard on Windows computers. We've discovered that the device doesn't behave similarly when connected to a Linux device (Mouse inputs aren't working). Would you be able to point us in your code where we can begin looking to try to solve this issue on our own? Thanks and take care!
-----------------------------------
...[생략]...
-----------------------------------
Found: 12

대충 흐름이 눈에 들어오시나요? ^^

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




한 가지 오해하면 안 되는 것이 있는데요, 위에서 예를 든 EmbeddingSearchAsync 함수는 질문에 대해 자연어 분석을 하지는 않는다는 점입니다. 실제로 단순히 TensorPrimitives.CosineSimilarity 함수를 이용한 유사도를 비교한 것에 불과한 것이기 때문에, 질문을 다음과 같이 해도,

string question = "Are there any issues except for mouse?";

string[] results = await EmbeddingSearchAsync(openAIClient, embeddingDeployment, 
    question, issuesWithChunksCollection!, issuesWithChunksCollection.Length);

// 이전 질문과 동일한 결과 반환 ("except for"를 이해하지 못함)

단순히 "Are", "there", "any", "issues", "except", "for", "mouse"와 같은 토큰들로 연관 검색을 한 것에 불과합니다. 즉 "except for"에 대한 의미는 반영하지 못한 것입니다.




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







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

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13465정성태11/28/20232380개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232503닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232409오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232417오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232474닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232394닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232456닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232458닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232342VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232695닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232590닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232894닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232355오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232458닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232597닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232393닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232512개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232830닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232698닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232664닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20232993Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232712닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232776개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232547개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232921닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232520Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...