Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Javaで作る RAGを活用した Q&Aアプリケーション

Javaで作る RAGを活用した Q&Aアプリケーション

2025/6/17に、Java on Azure Day2025で発表した、政岡の資料です。

Avatar for Recruit

Recruit

June 25, 2025
Tweet

More Decks by Recruit

Other Decks in Technology

Transcript

  1. マスタ タイトルの書式設定 2025/06/17 Java で作る RAG を活用した Q&A アプリケーション ©

    Recruit Co., Ltd. 株式会社リクルート ICT 統括室 インフラソリューションユニット インフラソリューション1部 コミュニケーションプラットフォームグループ 政岡 裕士
  2. マスタ タイトルの書式設定 2 © Recruit Co., Ltd. Profile まっぴぃ |

    Yuji Masaoka (Igarashi) • 株式会社リクルート所属 • Microsoft Azure 関連の開発相談/支援 • Microsoft 365 の管理/運用、Graph API などを利用したアプリ開発相談 • X: @mappie_kochi • Blog: mappie-kochi.jp | とある IT エンジニアの日常 • Tech Blog: zenn.dev/ymasaoka
  3. マスタ タイトルの書式設定 3 © Recruit Co., Ltd. Agenda • Introduction

    • 今日お話させていただく内容について • デモアプリの説明 • デモアプリで利用している Azure サービス / フレームワークの紹介 • Java + Azure • Semantic Kernel から Azure OpenAI Service を利用する方法 • Java から Azure Cosmos DB を利用する方法 • Azure Cosmos DB を利用して RAG を実現する方法 • Demo • Conclusion
  4. マスタ タイトルの書式設定 4 © Recruit Co., Ltd. Today’s Topic &

    App Architecture • セッション内容 • Semantic Kernel for Java を利用した Chat Completion アプリ実装方法 • Spring AI の CosmosDBVectorStore を利用した RAG アプリ実装方法 Plugin Semantic Kernel Azure OpenAI Spring Boot App user Prompt Answer Spring Boot App user vector search prompt
  5. マスタ タイトルの書式設定 5 © Recruit Co., Ltd. Azure OpenAI Service

    (AOAI) • Azure の基盤上で OpenAI 製の各種生成 AI モデルへの REST API アクセスを提供 参考: Microsoft Learn (learn.microsoft.com)
  6. マスタ タイトルの書式設定 6 © Recruit Co., Ltd. Semantic Kernel •

    AI エージェントを簡単に構築し、最新の AI モデルをコードベースに統合できる、軽量の オープンソース開発キット • Microsoft が提供する OSS SDK • プラグインとして既存のコードや API を AI に組み込み AI の機能を拡張できる • C#、Python、Java に対応 • サポートされる機能は C# > Python > Java での順 • Java はまだまだサポートされる内容が少なめ (エージェント対応はやっと 2025/5 に 1.4.4-RC1 で登場) • Java だけ GitHub Repo が別 参考: Microsoft Learn (learn.microsoft.com)
  7. マスタ タイトルの書式設定 7 © Recruit Co., Ltd. Components: Semantic Kernel

    • AI Service Connectors • 共通の IF を介して異なる AI サービスを簡単に呼び出す抽象化レイヤー • Functions and Plugins • AI モデルの能力を拡張し、API の呼び出しやアプリケーションコードを実行させる (=Function Calling) • Vector Store (Memory) Connectors • ベクターストアを利用して、AI モデルが必要に応じてデータを呼び出す • Prompt Templates • プロンプトを複数のシナリオで再利用できるようにするもの、変数で値を埋め込むことが可能 • Filters • 関数の実行方法やタイミングを制御し、セキュリティや可視性を強化する 参考: Microsoft Learn (learn.microsoft.com)
  8. マスタ タイトルの書式設定 8 © Recruit Co., Ltd. Components: Semantic Kernel

    • AI Service Connectors • 共通の IF を介して異なる AI サービスを簡単に呼び出す抽象化レイヤー • Functions and Plugins • AI モデルの能力を拡張し、API の呼び出しやアプリケーションコードを実行させる (=Function Calling) • Vector Store (Memory) Connectors • ベクターストアを利用して、AI モデルが必要に応じてデータを呼び出す • Prompt Templates • プロンプトを複数のシナリオで再利用できるようにするもの、変数で値を埋め込むことが可能 • Filters • 関数の実行方法やタイミングを制御し、セキュリティや可視性を強化する 参考: Microsoft Learn (learn.microsoft.com)
  9. マスタ タイトルの書式設定 9 © Recruit Co., Ltd. Azure Cosmos DB

    • グローバル分散が可能な、フルマネージドでマルチモデル/マルチ API 対応のデータベース 参考: Microsoft Learn (learn.microsoft.com)
  10. マスタ タイトルの書式設定 10 © Recruit Co., Ltd. Azure Cosmos DB

    • Azure Cosmos DB の機能概要については下記参照 • 公式ドキュメント: Azure Cosmos DB のドキュメント - Microsoft Learn • 過去の登壇資料: Azure Cosmos DB で始める Java + NoSQL 開発 - slideshare
  11. マスタ タイトルの書式設定 11 © Recruit Co., Ltd. Azure Cosmos DB

    VectorStore • Azure Cosmos DB はベクトル検索にも対応 • ベクトルインデックスとして flat / quantizedFlat / DiskANN の 3 つが選択可能 • ベクトルポリシーとして以下を定義することが必要 • path: ベクトルを含むプロパティへのパス • datatype: vector プロパティのデータ型 (float32 / int 8 / uint8) • dimensions: 各ベクトルの次元 • distanceFunction: ベクトルの距離と類似度の計算に使われるメトリック (cosine / dotproduct / eucludean) 参考: Microsoft Learn (learn.microsoft.com)
  12. マスタ タイトルの書式設定 12 © Recruit Co., Ltd. Calling AOAI API

    from Semantic Kernel • Azure OpenAI 上のモデルは REST API 経由で呼び出す • Azure OpenAI client library for Java を利用して接続 • Spring AI、Semantic Kernel や LangChain4j などのフレームワークを利用して接続 // API キーを利用した Semantic Kernel での Azure OpenAI への接続設定 OpenAIAsyncClient asyncClient = new OpenAIClientBuilder() .credential(new AzureKeyCredential(AZURE_OPENAI_KEY)) .endpoint(AZURE_OPENAI_ENDPOINT) .buildAsyncClient(); ChatCompletionService chat = OpenAIChatCompletion.builder() .withModelId(AZURE_OPENAI_MODEL_NAME) .withOpenAIAsyncClient(asyncClient) .build() // カーネルを生成 Kernel kernel = Kernel.builder() .withPlugin(hogehogePlugin) // なくてもOK .build();
  13. マスタ タイトルの書式設定 13 © Recruit Co., Ltd. Calling AOAI API

    from Semantic Kernel • Azure OpenAI 上のモデルは REST API 経由で呼び出す • Azure OpenAI client library for Java を利用して接続 • Spring AI、Semantic Kernel や LangChain4j などのフレームワークを利用して接続 // チャット履歴を保持する ChatHistory を生成 ChatHistory history = new ChatHistory(); // ChatHistory にユーザープロンプトを入れて送信し、返事を取得 history.addUserMessage(USER_PROMPT) // Function Calling の実行設定 var invocationContext = InvocationContext.builder() .wuthToolCallBehavior(ToolCallBehavior.allowAllKernelFunctions(true)) .build() // モデルからのメッセージを取得 var reply = chat.getChatMessageContentAsync(history, kernel, invocationContext).block() reply.forEach(chatMessageContent -> { if (chatMessageContent.getAuthorRole() == AuthorRole.ASSISTANT) { var content = chatMessageContent.getContent(); } }); // ChatHistoryにメッセージを入れて、やりとりを必要に応じて繰り返す
  14. マスタ タイトルの書式設定 14 © Recruit Co., Ltd. Interacting with Azure

    Cosmos DB using Java • 各種SDK やフレームワークを利用して接続する • Azure Cosmos DB SDK for Java を利用して接続 (Core API) • 各種 DB の SDK を利用して接続 (MongoDB、Cassandra、Gremlin、PostgreSQL) • Spring Data / Spring AI を利用して接続 • Spring Data: Core API • Spring AI: VectorStore (ベクトルストア)
  15. マスタ タイトルの書式設定 15 © Recruit Co., Ltd. Interacting with Azure

    Cosmos DB using Cosmos SDK // Cosmos アカウントへの接続クライアントを作成 private CosmosAsyncClient asyncClient; asyncClient = new CosmosClientBuilder() .endpoint(AZURE_COSMOS_DB_ENDPOINT) .key(AZURE_COSMOS_DB_KEY) .preferredRegions(Collection.singletonList(“Japan East”)) .consistencyLevel(ConsistencyLevel.SESSION) .buildAsyncClient(); // Cosmos DB のデータベースへ接続 private CosmosDatabase database; CosmosDatabaseResponse databaseResponse = asyncClient.createDatabaseIfNotExists(DATABASE_NAME); database = client.getDatabase(databaseResponse.getProperties().getId()) // Cosmos DB のコンテナーへ接続 private CosmosContainer container; CosmosContainerProperties properties = new CosmosContainerProperties(CONTAINER_ID, PERTITION_KEY); CosmosContainerResponse containerResponse = database.createContainerIfNotExists(properties); container = database.getContainer(containerResponse.getProperties().getId());
  16. マスタ タイトルの書式設定 16 © Recruit Co., Ltd. Interacting with Azure

    Cosmos DB using Cosmos SDK // 飛行機の搭乗情報の例 // Create an item cosmosAsyncContainer.createItem(new Passenger(”[email protected]", ”Yuji Masaoka", ”HND", ”KCZ")) .flatMap(response -> { System.out.println("Created item: " + response.getItem()); // Read that item return cosmosAsyncContainer.readItem(response.getItem().getId(), new PartitionKey(response.getItem().getId()), Passenger.class); }) .flatMap(response -> { System.out.println("Read item: " + response.getItem()); // Replace that item Passenger p = response.getItem(); p.setDestination(“CTS”); // 新千歳空港行きに変更 return cosmosAsyncContainer.replaceItem(p, response.getItem().getId(), new PartitionKey(response.getItem().getId())); }) // delete that item .flatMap(response -> cosmosAsyncContainer.deleteItem(response.getItem().getId(), new PartitionKey(response.getItem().getId()) ));
  17. マスタ タイトルの書式設定 17 © Recruit Co., Ltd. Implementing RAG with

    Cosmos DB • Spring AI と Cosmos DB VectorStore を組み合わせるだけで簡単に実現可能 • Client 生成などは Spring AI で Autowired するだけでOK @Autowired private ChatClient chatClient; @Autowired private VectorStore vectorStore; public String generation(@RequestBody String userInput) { String answer = this.chatClient.prompt() .advisors(new QuestionAnswerAdvisor(vectorStore)) .user(userInput) .call() .content(); } 参考: Azure-Samples/cosmosdb-spring-ai-sample (GitHub)
  18. マスタ タイトルの書式設定 19 © Recruit Co., Ltd. Conclusion • Semantic

    Kernel を利用すれば汎用的な AI アプリ構築が可能になる • plugin を利用し独自のカスタマイズした生成 AI エージェントを開発可能 • 異なる生成 AI モデルであっても抽象度が高く汎用的なコードが書ける • Java においては Azure AI Agent 対応はこれから (現在は RC1) • Azure Cosmos DB VectorStore だけで RAG アプリ構築も可能になった • Azure AI Search などを介さずとも DB だけで RAG ができる • 別途 RAG 用のベクトル化したデータは準備が必要 • ベクトル化は embedding モデルなどを利用し自身で対応が必要