|
| 1 | +# Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import time |
| 5 | +from collections.abc import Awaitable, Callable |
| 6 | +from dataclasses import dataclass, field |
| 7 | +from typing import Annotated |
| 8 | +from uuid import uuid4 |
| 9 | + |
| 10 | +from semantic_kernel.connectors.ai.embeddings.embedding_generator_base import EmbeddingGeneratorBase |
| 11 | +from semantic_kernel.connectors.ai.open_ai.services.open_ai_chat_completion import OpenAIChatCompletion |
| 12 | +from semantic_kernel.connectors.ai.open_ai.services.open_ai_text_embedding import OpenAITextEmbedding |
| 13 | +from semantic_kernel.connectors.memory.in_memory.in_memory_store import InMemoryVectorStore |
| 14 | +from semantic_kernel.data.record_definition import vectorstoremodel |
| 15 | +from semantic_kernel.data.record_definition.vector_store_record_fields import ( |
| 16 | + VectorStoreRecordDataField, |
| 17 | + VectorStoreRecordKeyField, |
| 18 | + VectorStoreRecordVectorField, |
| 19 | +) |
| 20 | +from semantic_kernel.data.vector_search.vector_search_options import VectorSearchOptions |
| 21 | +from semantic_kernel.data.vector_search.vectorized_search import VectorizedSearchMixin |
| 22 | +from semantic_kernel.data.vector_storage.vector_store import VectorStore |
| 23 | +from semantic_kernel.data.vector_storage.vector_store_record_collection import VectorStoreRecordCollection |
| 24 | +from semantic_kernel.filters.filter_types import FilterTypes |
| 25 | +from semantic_kernel.filters.functions.function_invocation_context import FunctionInvocationContext |
| 26 | +from semantic_kernel.filters.prompts.prompt_render_context import PromptRenderContext |
| 27 | +from semantic_kernel.functions.function_result import FunctionResult |
| 28 | +from semantic_kernel.kernel import Kernel |
| 29 | + |
| 30 | +COLLECTION_NAME = "llm_responses" |
| 31 | +RECORD_ID_KEY = "cache_record_id" |
| 32 | + |
| 33 | + |
| 34 | +# Define a simple data model to store, the prompt, the result, and the prompt embedding. |
| 35 | +@vectorstoremodel |
| 36 | +@dataclass |
| 37 | +class CacheRecord: |
| 38 | + prompt: Annotated[str, VectorStoreRecordDataField(embedding_property_name="prompt_embedding")] |
| 39 | + result: Annotated[str, VectorStoreRecordDataField(is_full_text_searchable=True)] |
| 40 | + prompt_embedding: Annotated[list[float], VectorStoreRecordVectorField(dimensions=1526)] = field( |
| 41 | + default_factory=list |
| 42 | + ) |
| 43 | + id: Annotated[str, VectorStoreRecordKeyField] = field(default_factory=lambda: str(uuid4())) |
| 44 | + |
| 45 | + |
| 46 | +# Define the filters, one for caching the results and one for using the cache. |
| 47 | +class PromptCacheFilter: |
| 48 | + """A filter to cache the results of the prompt rendering and function invocation.""" |
| 49 | + |
| 50 | + def __init__( |
| 51 | + self, |
| 52 | + embedding_service: EmbeddingGeneratorBase, |
| 53 | + vector_store: VectorStore, |
| 54 | + collection_name: str = COLLECTION_NAME, |
| 55 | + score_threshold: float = 0.2, |
| 56 | + ): |
| 57 | + self.embedding_service = embedding_service |
| 58 | + self.vector_store = vector_store |
| 59 | + self.collection: VectorStoreRecordCollection[str, CacheRecord] = vector_store.get_collection( |
| 60 | + collection_name, data_model_type=CacheRecord |
| 61 | + ) |
| 62 | + self.score_threshold = score_threshold |
| 63 | + |
| 64 | + async def on_prompt_render( |
| 65 | + self, context: PromptRenderContext, next: Callable[[PromptRenderContext], Awaitable[None]] |
| 66 | + ): |
| 67 | + """Filter to cache the rendered prompt and the result of the function. |
| 68 | +
|
| 69 | + It uses the score threshold to determine if the result should be cached. |
| 70 | + The direction of the comparison is based on the default distance metric for |
| 71 | + the in memory vector store, which is cosine distance, so the closer to 0 the |
| 72 | + closer the match. |
| 73 | + """ |
| 74 | + await next(context) |
| 75 | + assert context.rendered_prompt # nosec |
| 76 | + prompt_embedding = await self.embedding_service.generate_raw_embeddings([context.rendered_prompt]) |
| 77 | + await self.collection.create_collection_if_not_exists() |
| 78 | + assert isinstance(self.collection, VectorizedSearchMixin) # nosec |
| 79 | + results = await self.collection.vectorized_search( |
| 80 | + vector=prompt_embedding[0], options=VectorSearchOptions(vector_field_name="prompt_embedding", top=1) |
| 81 | + ) |
| 82 | + async for result in results.results: |
| 83 | + if result.score < self.score_threshold: |
| 84 | + context.function_result = FunctionResult( |
| 85 | + function=context.function.metadata, |
| 86 | + value=result.record.result, |
| 87 | + rendered_prompt=context.rendered_prompt, |
| 88 | + metadata={RECORD_ID_KEY: result.record.id}, |
| 89 | + ) |
| 90 | + |
| 91 | + async def on_function_invocation( |
| 92 | + self, context: FunctionInvocationContext, next: Callable[[FunctionInvocationContext], Awaitable[None]] |
| 93 | + ): |
| 94 | + """Filter to store the result in the cache if it is new.""" |
| 95 | + await next(context) |
| 96 | + result = context.result |
| 97 | + if result and result.rendered_prompt and RECORD_ID_KEY not in result.metadata: |
| 98 | + prompt_embedding = await self.embedding_service.generate_embeddings([result.rendered_prompt]) |
| 99 | + cache_record = CacheRecord( |
| 100 | + prompt=result.rendered_prompt, |
| 101 | + result=str(result), |
| 102 | + prompt_embedding=prompt_embedding[0], |
| 103 | + ) |
| 104 | + await self.collection.create_collection_if_not_exists() |
| 105 | + await self.collection.upsert(cache_record) |
| 106 | + |
| 107 | + |
| 108 | +async def execute_async(kernel: Kernel, title: str, prompt: str): |
| 109 | + """Helper method to execute and log time.""" |
| 110 | + print(f"{title}: {prompt}") |
| 111 | + start = time.time() |
| 112 | + result = await kernel.invoke_prompt(prompt) |
| 113 | + elapsed = time.time() - start |
| 114 | + print(f"\tElapsed Time: {elapsed:.3f}") |
| 115 | + return result |
| 116 | + |
| 117 | + |
| 118 | +async def main(): |
| 119 | + # create the kernel and add the chat service and the embedding service |
| 120 | + kernel = Kernel() |
| 121 | + chat = OpenAIChatCompletion(service_id="default") |
| 122 | + embedding = OpenAITextEmbedding(service_id="embedder") |
| 123 | + kernel.add_service(chat) |
| 124 | + kernel.add_service(embedding) |
| 125 | + # create the in-memory vector store |
| 126 | + vector_store = InMemoryVectorStore() |
| 127 | + # create the cache filter and add the filters to the kernel |
| 128 | + cache = PromptCacheFilter(embedding_service=embedding, vector_store=vector_store) |
| 129 | + kernel.add_filter(FilterTypes.PROMPT_RENDERING, cache.on_prompt_render) |
| 130 | + kernel.add_filter(FilterTypes.FUNCTION_INVOCATION, cache.on_function_invocation) |
| 131 | + |
| 132 | + # Run the sample |
| 133 | + print("\nIn-memory cache sample:") |
| 134 | + r1 = await execute_async(kernel, "First run", "What's the tallest building in New York?") |
| 135 | + print(f"\tResult 1: {r1}") |
| 136 | + r2 = await execute_async(kernel, "Second run", "How are you today?") |
| 137 | + print(f"\tResult 2: {r2}") |
| 138 | + r3 = await execute_async(kernel, "Third run", "What is the highest building in New York City?") |
| 139 | + print(f"\tResult 3: {r3}") |
| 140 | + |
| 141 | + |
| 142 | +if __name__ == "__main__": |
| 143 | + asyncio.run(main()) |
0 commit comments