|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | +package com.microsoft.semantickernel.samples.syntaxexamples.memory; |
| 3 | + |
| 4 | +import com.azure.ai.openai.OpenAIAsyncClient; |
| 5 | +import com.azure.ai.openai.OpenAIClientBuilder; |
| 6 | +import com.azure.core.credential.AzureKeyCredential; |
| 7 | +import com.azure.core.credential.KeyCredential; |
| 8 | +import com.azure.core.util.ClientOptions; |
| 9 | +import com.azure.core.util.MetricsOptions; |
| 10 | +import com.azure.core.util.TracingOptions; |
| 11 | +import com.microsoft.semantickernel.aiservices.openai.textembedding.OpenAITextEmbeddingGenerationService; |
| 12 | +import com.microsoft.semantickernel.connectors.data.redis.RedisVectorStore; |
| 13 | +import com.microsoft.semantickernel.connectors.data.redis.RedisVectorStoreOptions; |
| 14 | +import com.microsoft.semantickernel.data.VectorStoreRecordCollection; |
| 15 | +import com.microsoft.semantickernel.data.recordattributes.VectorStoreRecordDataAttribute; |
| 16 | +import com.microsoft.semantickernel.data.recordattributes.VectorStoreRecordKeyAttribute; |
| 17 | +import com.microsoft.semantickernel.data.recordattributes.VectorStoreRecordVectorAttribute; |
| 18 | +import java.nio.charset.StandardCharsets; |
| 19 | +import java.util.Arrays; |
| 20 | +import java.util.Base64; |
| 21 | +import java.util.Collections; |
| 22 | +import java.util.List; |
| 23 | +import java.util.Map; |
| 24 | +import java.util.stream.Collectors; |
| 25 | +import reactor.core.publisher.Flux; |
| 26 | +import reactor.core.publisher.Mono; |
| 27 | +import redis.clients.jedis.JedisPooled; |
| 28 | + |
| 29 | +public class Redis_DataStorage { |
| 30 | + |
| 31 | + private static final String CLIENT_KEY = System.getenv("CLIENT_KEY"); |
| 32 | + private static final String AZURE_CLIENT_KEY = System.getenv("AZURE_CLIENT_KEY"); |
| 33 | + |
| 34 | + // Only required if AZURE_CLIENT_KEY is set |
| 35 | + private static final String CLIENT_ENDPOINT = System.getenv("CLIENT_ENDPOINT"); |
| 36 | + |
| 37 | + private static final String MODEL_ID = System.getenv() |
| 38 | + .getOrDefault("EMBEDDING_MODEL_ID", "text-embedding-3-large"); |
| 39 | + private static final int EMBEDDING_DIMENSIONS = 1536; |
| 40 | + |
| 41 | + // Can start a test server with: |
| 42 | + // docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest |
| 43 | + private static final String REDIS_URL = "redis://127.0.0.1:6379"; |
| 44 | + |
| 45 | + public static class GitHubFile { |
| 46 | + |
| 47 | + @VectorStoreRecordKeyAttribute() |
| 48 | + private final String id; |
| 49 | + @VectorStoreRecordDataAttribute(hasEmbedding = true, embeddingFieldName = "embedding") |
| 50 | + private final String description; |
| 51 | + @VectorStoreRecordDataAttribute |
| 52 | + private final String link; |
| 53 | + @VectorStoreRecordVectorAttribute(dimensions = EMBEDDING_DIMENSIONS, indexKind = "Hnsw") |
| 54 | + private final List<Float> embedding; |
| 55 | + |
| 56 | + public GitHubFile() { |
| 57 | + this(null, null, null, Collections.emptyList()); |
| 58 | + } |
| 59 | + |
| 60 | + public GitHubFile( |
| 61 | + String id, |
| 62 | + String description, |
| 63 | + String link, |
| 64 | + List<Float> embedding) { |
| 65 | + this.id = id; |
| 66 | + this.description = description; |
| 67 | + this.link = link; |
| 68 | + this.embedding = embedding; |
| 69 | + } |
| 70 | + |
| 71 | + public String getId() { |
| 72 | + return id; |
| 73 | + } |
| 74 | + public String getDescription() { |
| 75 | + return description; |
| 76 | + } |
| 77 | + |
| 78 | + static String encodeId(String realId) { |
| 79 | + byte[] bytes = Base64.getUrlEncoder().encode(realId.getBytes(StandardCharsets.UTF_8)); |
| 80 | + return new String(bytes, StandardCharsets.UTF_8); |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + public static void main(String[] args) { |
| 85 | + System.out.println("=============================================================="); |
| 86 | + System.out.println("========== Redis Vector Store Example =============="); |
| 87 | + System.out.println("=============================================================="); |
| 88 | + |
| 89 | + OpenAIAsyncClient client; |
| 90 | + |
| 91 | + if (AZURE_CLIENT_KEY != null) { |
| 92 | + client = new OpenAIClientBuilder() |
| 93 | + .credential(new AzureKeyCredential(AZURE_CLIENT_KEY)) |
| 94 | + .endpoint(CLIENT_ENDPOINT) |
| 95 | + .buildAsyncClient(); |
| 96 | + |
| 97 | + } else { |
| 98 | + client = new OpenAIClientBuilder() |
| 99 | + .credential(new KeyCredential(CLIENT_KEY)) |
| 100 | + .buildAsyncClient(); |
| 101 | + } |
| 102 | + |
| 103 | + var embeddingGeneration = OpenAITextEmbeddingGenerationService.builder() |
| 104 | + .withOpenAIAsyncClient(client) |
| 105 | + .withModelId(MODEL_ID) |
| 106 | + .withDimensions(EMBEDDING_DIMENSIONS) |
| 107 | + .build(); |
| 108 | + |
| 109 | + dataStorageWithRedis(embeddingGeneration); |
| 110 | + } |
| 111 | + |
| 112 | + public static void dataStorageWithRedis( |
| 113 | + OpenAITextEmbeddingGenerationService embeddingGeneration) { |
| 114 | + |
| 115 | + JedisPooled jedis = new JedisPooled(REDIS_URL); |
| 116 | + |
| 117 | + RedisVectorStore<GitHubFile> vectorStore = RedisVectorStore.<GitHubFile>builder() |
| 118 | + .withClient(jedis) |
| 119 | + .withOptions(new RedisVectorStoreOptions<>(GitHubFile.class, null)) |
| 120 | + .build(); |
| 121 | + |
| 122 | + String collectionName = "skgithubfiles"; |
| 123 | + var collection = vectorStore.getCollection(collectionName, null); |
| 124 | + |
| 125 | + // Create collection if it does not exist and store data |
| 126 | + List<String> ids = collection |
| 127 | + .createCollectionIfNotExistsAsync() |
| 128 | + .then(storeData(collection, embeddingGeneration, sampleData())) |
| 129 | + .block(); |
| 130 | + |
| 131 | + List<GitHubFile> data = collection.getBatchAsync(ids, null).block(); |
| 132 | + |
| 133 | + data.forEach(gitHubFile -> System.out.println("Retrieved: " + gitHubFile.getDescription())); |
| 134 | + |
| 135 | + // TODO: Implement search functionality using Redis. |
| 136 | + |
| 137 | + } |
| 138 | + |
| 139 | + private static Mono<List<String>> storeData( |
| 140 | + VectorStoreRecordCollection<String, GitHubFile> recordStore, |
| 141 | + OpenAITextEmbeddingGenerationService embeddingGeneration, |
| 142 | + Map<String, String> data) { |
| 143 | + |
| 144 | + return Flux.fromIterable(data.entrySet()) |
| 145 | + .flatMap(entry -> { |
| 146 | + System.out.println("Save '" + entry.getKey() + "' to memory."); |
| 147 | + |
| 148 | + return embeddingGeneration |
| 149 | + .generateEmbeddingsAsync(Collections.singletonList(entry.getValue())) |
| 150 | + .flatMap(embeddings -> { |
| 151 | + GitHubFile gitHubFile = new GitHubFile( |
| 152 | + GitHubFile.encodeId(entry.getKey()), |
| 153 | + entry.getValue(), |
| 154 | + entry.getKey(), |
| 155 | + embeddings.get(0).getVector()); |
| 156 | + return recordStore.upsertAsync(gitHubFile, null); |
| 157 | + }); |
| 158 | + }) |
| 159 | + .collectList(); |
| 160 | + } |
| 161 | + |
| 162 | + private static Map<String, String> sampleData() { |
| 163 | + return Arrays.stream(new String[][] { |
| 164 | + { "https://github.com/microsoft/semantic-kernel/blob/main/README.md", |
| 165 | + "README: Installation, getting started with Semantic Kernel, and how to contribute" }, |
| 166 | + { "https://github.com/microsoft/semantic-kernel/blob/main/samples/notebooks/dotnet/02-running-prompts-from-file.ipynb", |
| 167 | + "Jupyter notebook describing how to pass prompts from a file to a semantic skill or function" }, |
| 168 | + { "https://github.com/microsoft/semantic-kernel/tree/main/samples/skills/ChatSkill/ChatGPT", |
| 169 | + "Sample demonstrating how to create a chat skill interfacing with ChatGPT" }, |
| 170 | + { "https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel/Memory/VolatileMemoryStore.cs", |
| 171 | + "C# class that defines a volatile embedding store" }, |
| 172 | + { "https://github.com/microsoft/semantic-kernel/blob/main/samples/dotnet/KernelHttpServer/README.md", |
| 173 | + "README: How to set up a Semantic Kernel Service API using Azure Function Runtime v4" }, |
| 174 | + { "https://github.com/microsoft/semantic-kernel/blob/main/samples/apps/chat-summary-webapp-react/README.md", |
| 175 | + "README: README associated with a sample chat summary react-based webapp" }, |
| 176 | + }).collect(Collectors.toMap(element -> element[0], element -> element[1])); |
| 177 | + } |
| 178 | + |
| 179 | + private static ClientOptions clientOptions() { |
| 180 | + return new ClientOptions() |
| 181 | + .setTracingOptions(new TracingOptions()) |
| 182 | + .setMetricsOptions(new MetricsOptions()) |
| 183 | + .setApplicationId("Semantic-Kernel"); |
| 184 | + } |
| 185 | +} |
0 commit comments