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)
13483정성태12/14/20232316닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232910닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232287개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232661개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232343개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232534닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232270닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232337닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232183개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232393닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232199C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232278Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232573닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232298닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232234닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232333오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232501닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232248개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232406닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232304오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232345오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232383닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232334닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232316닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232336닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232277VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...