### Install Dependencies Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/chat_history.ipynb Installs the necessary langchain-redis and langchain-openai packages. Use -qU for quiet and upgrade. ```python %pip install -qU langchain-redis langchain-openai ``` -------------------------------- ### Start Redis Docker Compose Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/README.md Use this command to start the Docker containers for local development. Ensure Docker and Docker Compose are installed. ```bash docker compose up ``` -------------------------------- ### Install All Development Dependencies Source: https://github.com/langchain-ai/langchain-redis/blob/main/CLAUDE.md Install all dependencies required for development, including linting, typing, and testing, using Poetry. ```bash poetry install --with lint,typing,test,test_integration ``` -------------------------------- ### Install All Test Dependencies Source: https://github.com/langchain-ai/langchain-redis/blob/main/CLAUDE.md Install all dependencies needed for both unit and integration tests using Poetry. ```bash poetry install --with test,test_integration ``` -------------------------------- ### Before migration: Initialize and use RedisCache Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/langchain_v1_migration.md Example of initializing and using RedisCache with LangChain v0.2.x. This code works with both older and newer versions. ```python from langchain.globals import set_llm_cache from langchain.schema import Generation from langchain_openai import OpenAI from langchain_redis import RedisCache # Initialize cache cache = RedisCache(redis_url="redis://localhost:6379") set_llm_cache(cache) # Use as normal llm = OpenAI() result = llm.invoke("Hello!") ``` -------------------------------- ### Install Required Packages Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/kitchensink.ipynb Installs the necessary LangChain Redis, LangChain OpenAI, and Wikipedia packages. A kernel restart may be required after installation. ```python %pip install -qU langchain-redis langchain-openai wikipedia ``` -------------------------------- ### After migration: Initialize and use RedisCache with LangChain v1.0 Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/langchain_v1_migration.md Example of initializing and using RedisCache with LangChain v1.0. Note the updated import path for set_llm_cache. ```python # Note that `langchain` became `langchain_core` from langchain_core.globals import set_llm_cache from langchain_core.outputs import Generation from langchain_openai import OpenAI from langchain_redis import RedisCache # Initialize cache (no changes needed) cache = RedisCache(redis_url="redis://localhost:6379") set_llm_cache(cache) # Use as normal (no changes needed) llm = OpenAI() result = llm.invoke("Hello!") ``` -------------------------------- ### Install RedisVectorStore and Dependencies Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/vectorstores.ipynb Installs the necessary packages for using RedisVectorStore, including langchain-redis, sentence-transformers, and scikit-learn. A kernel restart may be required after installation. ```python %pip install -qU langchain-redis langchain-huggingface sentence-transformers scikit-learn ``` -------------------------------- ### Install Unit Test Dependencies Source: https://github.com/langchain-ai/langchain-redis/blob/main/CLAUDE.md Install only the dependencies required for running unit tests using Poetry. ```bash poetry install --with test ``` -------------------------------- ### Install langchain-redis Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/README.md Install the package using pip. This includes core dependencies like redis, redisvl, and ulid. ```bash pip install -U langchain-redis ``` -------------------------------- ### Question Re-writer Setup Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/langgraph_self_rag.ipynb Configures an LLM to rewrite user questions for better optimization with vectorstore retrieval. It aims to capture the underlying semantic intent. ```python from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI # LLM llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0) # Prompt system = """You a question re-writer that converts an input question to a better version that is optimized \n for vectorstore retrieval. Look at the input and try to reason about the underlying semantic intent / meaning.""" re_write_prompt = ChatPromptTemplate.from_messages( [ ("system", system), ( "human", "Here is the initial question: \n\n {question} \n Formulate an improved question.", ), ] ) question_rewriter = re_write_prompt | llm | StrOutputParser() question_rewriter.invoke({"question": question}) ``` -------------------------------- ### Install Langchain Redis and Dependencies Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/cache.ipynb Installs the necessary packages for using Redis caching with LangChain, including OpenAI integration. A kernel restart may be required after installation. ```python %pip install -qU langchain-core "langchain-redis[langcache]" "langchain-openai>=1.0.3" "redis<7.0" ``` -------------------------------- ### Standard Redis Connection URLs Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/README.md Examples of connecting to a standard Redis instance, with and without authentication, and with SSL/TLS. ```python # Standard Redis redis_url = "redis://localhost:6379" # Redis with authentication redis_url = "redis://username:password@localhost:6379" # Redis SSL/TLS redis_url = "rediss://localhost:6380" ``` -------------------------------- ### Install Dependencies Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/langgraph_self_rag.ipynb Installs necessary Python packages for Redis VectorStore, LangChain, and OpenAI integration. A kernel restart may be required after installation. ```python %pip install -qU langchain-redis langchain_community tiktoken langchain-openai langchain langgraph langsmith ``` -------------------------------- ### Print Langchain-Redis Version Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/kitchensink.ipynb Prints the installed version of the langchain-redis library. ```python from langchain_redis.version import __lib_name__ print(f"langchain-redis version: {__lib_name__}") ``` -------------------------------- ### Answer Grader Setup Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/langgraph_self_rag.ipynb Sets up an LLM to grade if a generated answer directly addresses the user's question. It outputs a binary score ('yes' or 'no') using a Pydantic model. ```python from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.pydantic_v1 import BaseModel, Field from langchain_openai import ChatOpenAI # Data model class GradeAnswer(BaseModel): """Binary score to assess answer addresses question.""" binary_score: str = Field( description="Answer addresses the question, 'yes' or 'no'" ) # LLM with function call llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0) structured_llm_grader = llm.with_structured_output(GradeAnswer) # Prompt system = """You are a grader assessing whether an answer addresses / resolves a question \n Give a binary score 'yes' or 'no'. Yes' means that the answer resolves the question.""" answer_prompt = ChatPromptTemplate.from_messages( [ ("system", system), ("human", "User question: \n\n {question} \n\n LLM generation: {generation}"), ] ) answer_grader = answer_prompt | structured_llm_grader answer_grader.invoke({"question": question, "generation": generation}) ``` -------------------------------- ### Hallucination Grader Setup Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/langgraph_self_rag.ipynb Configures an LLM to grade whether a generated answer is grounded in the provided documents. It uses a Pydantic model for structured output. ```python from langchain_core.output_parsers import StrOutputParser from langchain_core.prompts import ChatPromptTemplate from langchain_core.pydantic_v1 import BaseModel, Field from langchain_openai import ChatOpenAI # Data model class GradeHallucinations(BaseModel): """Binary score for hallucination present in generation answer.""" binary_score: str = Field( description="Answer is grounded in the facts, 'yes' or 'no'" ) # LLM with function call llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0) structured_llm_grader = llm.with_structured_output(GradeHallucinations) # Prompt system = """You are a grader assessing whether an LLM generation is grounded in / supported by a set of retrieved facts. \n Give a binary score 'yes' or 'no'. 'Yes' means that the answer is grounded in / supported by the set of facts.""" hallucination_prompt = ChatPromptTemplate.from_messages( [ ("system", system), ("human", "Set of facts: \n\n {documents} \n\n LLM generation: {generation}"), ] ) hallucination_grader = hallucination_prompt | structured_llm_grader hallucination_grader.invoke({"documents": docs, "generation": generation}) ``` -------------------------------- ### Add and Retrieve Messages with RedisChatMessageHistory Source: https://context7.com/langchain-ai/langchain-redis/llms.txt Demonstrates adding SystemMessage, HumanMessage, and AIMessage to chat history and retrieving them chronologically. Also shows how to get the total message count. ```python history.add_message(SystemMessage(content="You are a helpful assistant.")) history.add_message(HumanMessage(content="What is machine learning?")) history.add_message(AIMessage(content="Machine learning is a subset of AI that enables systems to learn from data.")) history.add_message(HumanMessage(content="What are neural networks?")) history.add_message(AIMessage(content="Neural networks are computational models inspired by the human brain.")) # Retrieve all messages in chronological order messages = history.messages for msg in messages: print(f"[{msg.type}] {msg.content}") # Message count print(f"Total messages: {len(history)}") # 5 ``` -------------------------------- ### Connect to Redis Sentinel HA with RedisChatMessageHistory Source: https://context7.com/langchain-ai/langchain-redis/llms.txt Shows how to configure RedisChatMessageHistory to connect to a Redis Sentinel High Availability setup. This ensures continued operation in case of Redis master node failures. ```python # --- Sentinel HA connection --- ha_history = RedisChatMessageHistory( session_id="ha_session", redis_url="redis+sentinel://sentinel1:26379,sentinel2:26379/mymaster", ttl=3600, ) ha_history.add_message(HumanMessage(content="Hello from HA setup!")) ``` -------------------------------- ### Initialize RedisVectorStore Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/README.md Set up RedisVectorStore with embeddings, configuration, and specify distance metric. ```python from langchain_redis import RedisVectorStore, RedisConfig from langchain_core.embeddings import Embeddings embeddings = Embeddings() # Your preferred embedding model config = RedisConfig( index_name="my_vectors", redis_url="redis://localhost:6379", distance_metric="COSINE" # Options: COSINE, L2, IP ) vector_store = RedisVectorStore(embeddings, config=config) ``` -------------------------------- ### Activate Virtual Environment and Run Make Source: https://github.com/langchain-ai/langchain-redis/blob/main/CLAUDE.md Activate a project-specific virtual environment and then execute Make targets for tasks like testing. This ensures commands run with the correct dependencies. ```bash source .venv/bin/activate # or: source libs/redis/env/bin/activate make test # or any other Make target ``` -------------------------------- ### Initialize RedisCache Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/README.md Set up a standard Redis cache with a specified connection URL and time-to-live (TTL). ```python # Standard cache cache = RedisCache(redis_url="redis://localhost:6379", ttl=3600) ``` -------------------------------- ### Prepare Sample Data from 20 Newsgroups Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/vectorstores.ipynb Loads a subset of the 20 Newsgroups dataset, focusing on 'alt.atheism' and 'sci.space' categories. It selects the first 250 documents and creates a list of Document objects with associated metadata. ```python categories = ["alt.atheism", "sci.space"] newsgroups = fetch_20newsgroups( subset="train", categories=categories, shuffle=True, random_state=42 ) # Use only the first 250 documents texts = newsgroups.data[:250] metadata = [ {"category": newsgroups.target_names[target]} for target in newsgroups.target[:250] ] documents = [Document(page_content=text, metadata=meta) for text, meta in zip(texts, metadata)] len(documents) ``` -------------------------------- ### Test application after migration Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/langchain_v1_migration.md Run your test suite and application to ensure everything works correctly after updating dependencies and Python versions. ```bash # Run your test suite pytest tests/ # Verify your application works python your_app.py ``` -------------------------------- ### Inspect a Sample Document Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/vectorstores.ipynb Displays the first Document object from the prepared list, showing its metadata and page content. ```python documents[0] ``` -------------------------------- ### Basic Redis Caching Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/cache.ipynb Demonstrates basic caching using RedisCache. It initializes the cache, sets it for LangChain, invokes an LLM twice to show cached vs. non-cached performance, and then clears the cache. ```python import time from getpass import getpass from langchain_core.globals import set_llm_cache from langchain_core.outputs import Generation from langchain_openai import OpenAI, OpenAIEmbeddings from langchain_redis import RedisCache, RedisSemanticCache, LangCacheSemanticCache ``` ```python # Initialize RedisCache redis_cache = RedisCache(redis_url=REDIS_URL) # Set the cache for LangChain to use set_llm_cache(redis_cache) # Initialize the language model llm = OpenAI(temperature=0) # Function to measure execution time def timed_completion(prompt): start_time = time.time() result = llm.invoke(prompt) end_time = time.time() return result, end_time - start_time # First call (not cached) prompt = "Explain the concept of caching in three sentences." result1, time1 = timed_completion(prompt) print(f"First call (not cached):\nResult: {result1}\nTime: {time1:.2f} seconds\n") # Second call (should be cached) result2, time2 = timed_completion(prompt) print(f"Second call (cached):\nResult: {result2}\nTime: {time2:.2f} seconds\n") print(f"Speed improvement: {time1 / time2:.2f}x faster") # Clear the cache redis_cache.clear() print("Cache cleared") ``` -------------------------------- ### Initialize and Use LangCache Semantic Cache Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/cache.ipynb Sets up LangCache with API key and cache ID from environment variables or user input. It then demonstrates how a semantically similar query retrieves a cached response much faster than the original query. ```python # Check if LangCache API key and cache ID are already set in the environment langcache_api_key = os.getenv("LANGCACHE_API_KEY") langcache_cache_id = os.getenv("LANGCACHE_CACHE_ID") if not langcache_api_key or not langcache_cache_id: print("LangCache API key or cache ID not found in environment variables.") if not langcache_api_key: langcache_api_key = getpass("Please enter your LangCache API key: ") if not langcache_cache_id: langcache_cache_id = input("Please enter your LangCache cache ID: ") # Set the API key for the current session os.environ["LANGCACHE_API_KEY"] = langcache_api_key os.environ["LANGCACHE_CACHE_ID"] = langcache_cache_id print("LangCache API key and cache ID have been set for this session.") else: print("LangCache API key and cache ID found in environment variables.") if not langcache_api_key or not langcache_cache_id: print("Not running LangCache examples because we do not have an API key and cache ID.") exit(0) # Initialize LangCacheSemanticCache semantic_cache = LangCacheSemanticCache( cache_id=langcache_cache_id, api_key=langcache_api_key, distance_threshold=0.2 ) # Set the cache for LangChain to use set_llm_cache(semantic_cache) # Function to test semantic cache def test_semantic_cache(prompt): start_time = time.time() result = llm.invoke(prompt) end_time = time.time() return result, end_time - start_time # Original query original_prompt = "What is the capital of France?" result1, time1 = test_semantic_cache(original_prompt) print(f"Original query:\nPrompt: {original_prompt}\n") print(f"Result: {result1}\nTime: {time1:.2f} seconds\n") # Semantically similar query similar_prompt = "Can you tell me the capital city of France?" result2, time2 = test_semantic_cache(similar_prompt) print(f"Similar query:\nPrompt: {similar_prompt}\n") print(f"Result: {result2}\nTime: {time2:.2f} seconds\n") print(f"(Similar query) Speed improvement: {time1 / time2:.2f}x faster") # Clear the semantic cache semantic_cache.clear() print("Semantic cache cleared") ``` -------------------------------- ### RedisVectorStore with Sentinel Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/README.md Initialize RedisVectorStore using a Redis Sentinel connection URL and configuration. ```python from langchain_redis import RedisVectorStore, RedisConfig from langchain_openai import OpenAIEmbeddings config = RedisConfig( redis_url="redis+sentinel://sentinel1:26379,sentinel2:26379/mymaster", index_name="my_index" ) vector_store = RedisVectorStore( embeddings=OpenAIEmbeddings(), config=config ) ``` -------------------------------- ### Initialize RedisSemanticCache Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/README.md Configure a semantic cache using Redis, requiring embeddings and a distance threshold for similarity. ```python # Semantic cache embeddings = Embeddings() # Your preferred embedding model semantic_cache = RedisSemanticCache( redis_url="redis://localhost:6379", embedding=embeddings, distance_threshold=0.1 ) ``` -------------------------------- ### Initialize RedisCache with Custom TTL Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/cache.ipynb Demonstrates initializing RedisCache with a specific Time-To-Live (TTL). It shows updating a cache entry, retrieving it, and then verifying that the entry is no longer available after its TTL has expired. ```python # Initialize RedisCache with custom TTL ttl_cache = RedisCache(redis_url=REDIS_URL, ttl=5) # 60 seconds TTL # Update a cache entry ttl_cache.update("test_prompt", "test_llm", [Generation(text="Cached response")]) # Retrieve the cached entry cached_result = ttl_cache.lookup("test_prompt", "test_llm") print(f"Cached result: {cached_result[0].text if cached_result else 'Not found'}") # Wait for TTL to expire print("Waiting for TTL to expire...") time.sleep(6) # Try to retrieve the expired entry expired_result = ttl_cache.lookup("test_prompt", "test_llm") if expired_result: print(f"Result after TTL: {expired_result[0].text}") else: print("Not found (expired)") ``` -------------------------------- ### Import LangChain and OpenAI Components Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/kitchensink.ipynb Imports necessary classes and functions from langchain-redis, langchain-openai, and langchain-core for building the chatbot. ```python from langchain_redis import RedisVectorStore, RedisCache, RedisChatMessageHistory from langchain_openai import OpenAIEmbeddings, OpenAI from langchain_core.globals import set_llm_cache from langchain_core.prompts import PromptTemplate from langchain_core.output_parsers import StrOutputParser import wikipedia ``` -------------------------------- ### Initialize and Use RedisChatMessageHistory Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/chat_history.ipynb Initializes RedisChatMessageHistory with a session ID and Redis URL. Adds user and AI messages, then retrieves and prints the history. Finally, clears the history. ```python # Initialize RedisChatMessageHistory history = RedisChatMessageHistory(session_id="user_123", redis_url=REDIS_URL) # Add messages to the history history.add_user_message("Hello, AI assistant!") history.add_ai_message("Hello! How can I assist you today?") history.add_user_message("How are you today?") history.add_ai_message("I am doing well today. How can I help?") # Retrieve messages print("Chat History:") for message in history.messages: print(f"{type(message).__name__}: {message.content}") ``` ```python history.clear() ``` -------------------------------- ### Run Unit Tests Source: https://github.com/langchain-ai/langchain-redis/blob/main/CLAUDE.md Execute all unit tests defined in the project. ```bash make test ``` -------------------------------- ### Initialize ChatOpenAI Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/kitchensink.ipynb Initializes the ChatOpenAI language model with a temperature of 0 for deterministic output. ```python # Initialize ChatOpenAI with caching llm = OpenAI(temperature=0) ``` -------------------------------- ### Initialize RedisCache with an existing Redis client Source: https://context7.com/langchain-ai/langchain-redis/llms.txt Creates a RedisCache instance by passing an already configured Redis client object. Cache entries will expire after 10 minutes. ```python # --- Inject a pre-existing Redis client --- from redis import Redis redis_client = Redis.from_url("redis://localhost:6379", decode_responses=False) cache_with_client = RedisCache(redis_client=redis_client, ttl=600) ``` -------------------------------- ### Navigate to Redis Library Directory Source: https://github.com/langchain-ai/langchain-redis/blob/main/CLAUDE.md Change the current directory to the main library location within the monorepo. ```bash cd libs/redis ``` -------------------------------- ### Initialize RedisVectorStore Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/kitchensink.ipynb Initializes the RedisVectorStore using a RedisConfig object, specifying the index name and Redis URL. It connects to an existing index. ```python # Initialize RedisVectorStore using the pre-constructed index config = RedisConfig( index_name="kitchensink_docs", redis_url=REDIS_URL, from_existing=True ) vector_store = RedisVectorStore(OpenAIEmbeddings(), config=config) ``` -------------------------------- ### RedisCache: Using an existing Redis client Source: https://context7.com/langchain-ai/langchain-redis/llms.txt Initializes a RedisCache using a pre-existing Redis client instance. ```APIDOC ## RedisCache (with existing client) ### Description Allows using an already configured `redis.Redis` client instance when initializing `RedisCache`, useful for managing connections centrally. ### Method `RedisCache( redis_client: redis.Redis, ttl: int | None = None, prefix: str | None = None, **kwargs ) ` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **redis_client** (redis.Redis) - An existing, configured `redis.Redis` client object. - **ttl** (int, optional) - Time-to-live in seconds for cache entries. Defaults to None. - **prefix** (str, optional) - A namespace prefix for all cache keys. ### Request Example ```python from redis import Redis from langchain_redis import RedisCache # Assuming 'redis_client' is an already initialized redis.Redis instance redis_client = Redis.from_url("redis://localhost:6379", decode_responses=False) cache_with_client = RedisCache(redis_client=redis_client, ttl=600) ``` ### Response #### Success Response (200) Returns an initialized `RedisCache` instance using the provided Redis client. #### Response Example ```json { "message": "RedisCache initialized with provided Redis client successfully" } ``` ``` -------------------------------- ### Create RedisVectorStore from texts Source: https://context7.com/langchain-ai/langchain-redis/llms.txt Initializes a RedisVectorStore with provided texts, embeddings, and metadata. Requires a Redis instance running at the specified URL. ```python texts = [ "Redis is an in-memory data structure store.", "LangChain simplifies building LLM applications.", "Vector databases enable semantic search at scale.", ] metadatas = [ {"source": "redis-docs", "category": "database", "year": 2023}, {"source": "langchain-docs","category": "framework","year": 2023}, {"source": "ml-article", "category": "ml", "year": 2024}, ] store = RedisVectorStore.from_texts( texts=texts, embedding=embeddings, metadatas=metadatas, index_name="tech_docs", redis_url="redis://localhost:6379", distance_metric="COSINE", ) ``` -------------------------------- ### Update dependencies using requirements.txt Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/langchain_v1_migration.md Specify the minimum required versions for langchain-redis and langchain-core in your requirements.txt file. ```text langchain-redis>=0.3.0 langchain-core>=1.0 ``` -------------------------------- ### Initialize RedisCache Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/kitchensink.ipynb Initializes RedisCache for LLM caching and sets it as the global LLM cache. ```python # Initialize RedisCache redis_cache = RedisCache(redis_url=REDIS_URL) set_llm_cache(redis_cache) ``` -------------------------------- ### RedisVectorStore: Create from texts Source: https://context7.com/langchain-ai/langchain-redis/llms.txt Demonstrates how to create a RedisVectorStore from a list of texts, embeddings, and metadata. ```APIDOC ## RedisVectorStore.from_texts ### Description Creates a RedisVectorStore instance from a list of texts, embeddings, and associated metadata. ### Method `RedisVectorStore.from_texts( texts: list[str], embedding: Embeddings, metadatas: list[dict] | None = None, index_name: str, redis_url: str, distance_metric: str = "COSINE", **kwargs ) ` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **texts** (list[str]) - The list of text documents to store. - **embedding** (Embeddings) - The embedding model to use for generating vector embeddings. - **metadatas** (list[dict], optional) - A list of dictionaries, where each dictionary contains metadata for the corresponding text. - **index_name** (str) - The name of the Redis index to create or use. - **redis_url** (str) - The URL for the Redis instance. - **distance_metric** (str, optional) - The distance metric to use for similarity search. Defaults to "COSINE". ### Request Example ```python texts = [ "Redis is an in-memory data structure store.", "LangChain simplifies building LLM applications.", "Vector databases enable semantic search at scale.", ] metadatas = [ {"source": "redis-docs", "category": "database", "year": 2023}, {"source": "langchain-docs","category": "framework","year": 2023}, {"source": "ml-article", "category": "ml", "year": 2024}, ] store = RedisVectorStore.from_texts( texts=texts, embedding=embeddings, # Assuming 'embeddings' is an initialized embedding model metadatas=metadatas, index_name="tech_docs", redis_url="redis://localhost:6379", distance_metric="COSINE", ) ``` ### Response #### Success Response (200) Returns an initialized `RedisVectorStore` instance. #### Response Example ```json { "message": "RedisVectorStore initialized successfully" } ``` ``` -------------------------------- ### Create RedisVL Index Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/kitchensink.ipynb Establishes a Redis connection and creates a RedisVL search index using the defined schema. Overwrites the index if it already exists. ```python # Establish Redis connection and define index redis_client = Redis.from_url(REDIS_URL) # Create the index using RedisVL redisvl_index = SearchIndex(schema, redis_client) redisvl_index.create(overwrite=True) ``` -------------------------------- ### Auto-format Code Source: https://github.com/langchain-ai/langchain-redis/blob/main/CLAUDE.md Automatically format the project's code according to predefined style guidelines. ```bash make format ``` -------------------------------- ### RedisVectorStore: Create from existing index Source: https://context7.com/langchain-ai/langchain-redis/llms.txt Initializes a RedisVectorStore connected to an existing index in Redis. ```APIDOC ## RedisVectorStore.from_existing_index ### Description Connects to a pre-existing vector index in Redis and initializes a `RedisVectorStore` instance. ### Method `RedisVectorStore.from_existing_index( index_name: str, embedding: Embeddings, redis_url: str, **kwargs ) ` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **index_name** (str) - The name of the existing Redis index. - **embedding** (Embeddings) - The embedding model to use for similarity searches. - **redis_url** (str) - The URL for the Redis instance. ### Request Example ```python existing_store = RedisVectorStore.from_existing_index( index_name="tech_docs", embedding=embeddings, # Assuming 'embeddings' is an initialized embedding model redis_url="redis://localhost:6379", ) results = existing_store.similarity_search("Redis features", k=1) print(results[0].page_content) ``` ### Response #### Success Response (200) Returns an initialized `RedisVectorStore` instance connected to the existing index. #### Response Example ```json { "message": "RedisVectorStore connected to existing index successfully" } ``` ``` -------------------------------- ### RedisCache: Manual interactions Source: https://context7.com/langchain-ai/langchain-redis/llms.txt Demonstrates manual interaction with the RedisCache for updating, looking up, and clearing entries. ```APIDOC ## RedisCache: Manual Cache Interactions ### Description Allows direct manipulation of the cache, including storing new results, retrieving existing ones, and clearing the cache. ### Methods - `cache.update(prompt: str, llm_string: str, result: list[Generation])` - `cache.lookup(prompt: str, llm_string: str) -> list[Generation] | None` - `cache.clear()` ### Parameters #### Update/Lookup Parameters - **prompt** (str) - The input prompt used for the LLM call. - **llm_string** (str) - A string identifying the LLM configuration. - **result** (list[Generation]) - The list of generations to store in the cache (for `update`). ### Request Example ```python from langchain_core.outputs import Generation # Assuming 'cache' is an initialized RedisCache instance prompt = "What is 2 + 2?" llm_string = "openai/gpt-4o-mini" result = [Generation(text="4")] # Store a result cache.update(prompt, llm_string, result) # Retrieve a result hit = cache.lookup(prompt, llm_string) if hit: print(f"Cache hit: {hit[0].text}") # Cache hit: 4 else: print("Cache miss") # Check that a different prompt is a miss miss = cache.lookup("What is 3 + 3?", llm_string) print(miss) # None # Clear all entries with prefix "myapp:" cache.clear() ``` ### Response #### Success Response (200) - `update`: No explicit return value, modifies the cache. - `lookup`: Returns a list of `Generation` objects if found, otherwise `None`. - `clear`: No explicit return value, clears the cache. #### Response Example ```json // For lookup hit: [ { "text": "4" } ] // For lookup miss: null ``` ``` -------------------------------- ### RedisCache: Create and register Source: https://context7.com/langchain-ai/langchain-redis/llms.txt Initializes a RedisCache and registers it globally for LLM calls. ```APIDOC ## RedisCache ### Description Provides an exact key-based caching mechanism for LLM responses using Redis. Cache keys are derived from prompts and LLM configurations, with optional TTL for expiration. ### Method `RedisCache( redis_url: str, ttl: int | None = None, prefix: str | None = None, **kwargs ) ` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **redis_url** (str) - The URL for the Redis instance. Can include Sentinel URLs. - **ttl** (int, optional) - Time-to-live in seconds for cache entries. If None, entries do not expire. Defaults to None. - **prefix** (str, optional) - A namespace prefix for all cache keys. ### Request Example ```python from langchain_redis import RedisCache from langchain_core.globals import set_llm_cache cache = RedisCache( redis_url="redis://localhost:6379", ttl=3600, # 1 hour; None means no expiry prefix="myapp", # namespace prefix for keys ) set_llm_cache(cache) # Now every LLM call is cached automatically # llm = ChatOpenAI(model="gpt-4o-mini") # response1 = llm.invoke("What is the capital of France?") # response2 = llm.invoke("What is the capital of France?") # served from cache ``` ### Response #### Success Response (200) Returns an initialized `RedisCache` instance. #### Response Example ```json { "message": "RedisCache initialized successfully" } ``` ``` -------------------------------- ### Import RedisVL Components Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/kitchensink.ipynb Imports Redis client and RedisVL components for creating and managing vector indexes. ```python from redis import Redis from redisvl.index import SearchIndex from redisvl.schema import IndexSchema from langchain_redis import RedisConfig ``` -------------------------------- ### Run Make Test with Specific File Source: https://github.com/langchain-ai/langchain-redis/blob/main/CLAUDE.md Execute the 'test' Make target, specifying a particular test file to run. This is useful for focused testing. ```bash TEST_FILE=tests/unit_tests/test_specific.py make test ``` -------------------------------- ### RedisCache with Sentinel Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/README.md Initialize RedisCache using a Redis Sentinel connection URL. ```python from langchain_redis import RedisCache cache = RedisCache( redis_url="redis+sentinel://sentinel1:26379,sentinel2:26379/mymaster", ttl=3600 ) ``` -------------------------------- ### Initialize Retrieval Grader Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/langgraph_self_rag.ipynb Sets up a retrieval grader using an LLM to assess document relevance to a user question. It defines a Pydantic model for structured output and a prompt template for grading. ```python from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI from pydantic import BaseModel, Field # Data model class GradeDocuments(BaseModel): """Binary score for relevance check on retrieved documents.""" binary_score: str = Field( description="Documents are relevant to the question, 'yes' or 'no'" ) # LLM with function call llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0) structured_llm_grader = llm.with_structured_output(GradeDocuments) # Prompt system = """You are a grader assessing relevance of a retrieved document to a user question. \n It does not need to be a stringent test. The goal is to filter out erroneous retrievals. \n If the document contains keyword(s) or semantic meaning related to the user question, grade it as relevant. \n Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question.""" grade_prompt = ChatPromptTemplate.from_messages( [ ("system", system), ("human", "Retrieved document: \n\n {document} \n\n User question: {question}"), ] ) retrieval_grader = grade_prompt | structured_llm_grader question = "agent memory" docs = retriever.invoke(question) doc_txt = docs[1].page_content ``` -------------------------------- ### Configure RedisCache with Sentinel Source: https://context7.com/langchain-ai/langchain-redis/llms.txt Initializes a RedisCache using a Redis Sentinel connection string for high availability. TTL is set to 2 hours. ```python # --- Sentinel-backed cache --- sentinel_cache = RedisCache( redis_url="redis+sentinel://sentinel1:26379,sentinel2:26379/mymaster", ttl=7200, ) set_llm_cache(sentinel_cache) ``` -------------------------------- ### Initialize RedisChatMessageHistory Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/kitchensink.ipynb Initializes RedisChatMessageHistory for managing chat history. Ensure REDIS_URL is set. ```python message_history = RedisChatMessageHistory("kitchensink_chat", redis_url=REDIS_URL) ``` -------------------------------- ### Create RedisVectorStore and Insert Documents Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/vectorstores.ipynb Creates an instance of RedisVectorStore using the prepared documents and embeddings. It specifies the Redis URL, an index name, and a metadata schema for the 'category' field. ```python vector_store = RedisVectorStore.from_documents( documents, embeddings, redis_url=REDIS_URL, index_name="newsgroups", metadata_schema=[ {"name": "category", "type": "tag"}, ], ) ``` -------------------------------- ### Initialize LangChain Semantic Cache Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/README.md Instantiate the LangChain semantic cache with a unique ID, API key, and distance threshold for similarity searches. ```python langchain_cache = LangCacheSemanticCache( cache_id="your-cache-id", api_key="your-api-key", distance_threshold=0.1 ) ``` -------------------------------- ### Configure Conversational Chain with History Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/chat_history.ipynb Sets up a Langchain conversational chain using a prompt template, an OpenAI language model, and RedisChatMessageHistory. The `get_redis_history` function ensures history is retrieved or created for a given session ID. ```python import logging from langchain_core.chat_history import BaseChatMessageHistory from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_core.runnables.history import RunnableWithMessageHistory from langchain_openai import ChatOpenAI from langchain_redis import RedisChatMessageHistory logging.getLogger('redisvl').setLevel(logging.WARNING) # Create a prompt template prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a helpful AI assistant."), MessagesPlaceholder(variable_name="history"), ("human", "{input}"), ] ) # Initialize the language model llm = ChatOpenAI(model="gpt-4o-mini") # Create the conversational chain chain = prompt | llm # Function to get or create a RedisChatMessageHistory instance def get_redis_history(session_id: str) -> BaseChatMessageHistory: return RedisChatMessageHistory(session_id, redis_url=REDIS_URL) # Create a runnable with message history chain_with_history = RunnableWithMessageHistory( chain, get_redis_history, input_messages_key="input", history_messages_key="history" ) ``` -------------------------------- ### Run Integration Tests Source: https://github.com/langchain-ai/langchain-redis/blob/main/CLAUDE.md Execute integration tests, which require an OPENAI_API_KEY environment variable to be set. ```bash make integration_tests ``` -------------------------------- ### Run Specific Unit Test Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/README.md Run a single unit test file by specifying the TEST_FILE environment variable. ```bash TEST_FILE=tests/unit_tests/test_imports.py make test ``` -------------------------------- ### Connect to an existing RedisVectorStore index Source: https://context7.com/langchain-ai/langchain-redis/llms.txt Initializes a RedisVectorStore client connected to a pre-existing index in Redis. Useful for querying data without re-ingesting. ```python existing_store = RedisVectorStore.from_existing_index( index_name="tech_docs", embedding=embeddings, redis_url="redis://localhost:6379", ) results = existing_store.similarity_search("Redis features", k=1) print(results[0].page_content) ``` -------------------------------- ### Initialize Redis Chat History Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/README.md Set up Redis chat history storage with a session ID, Redis URL, and an optional time-to-live (TTL) for messages. ```python history = RedisChatMessageHistory( session_id="user_123", redis_url="redis://localhost:6379", ttl=3600, # Messages will expire after 1 hour ) ``` -------------------------------- ### RedisChatMessageHistory with Sentinel Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/README.md Initialize RedisChatMessageHistory using a Redis Sentinel connection URL. ```python from langchain_redis import RedisChatMessageHistory history = RedisChatMessageHistory( session_id="user_123", redis_url="redis+sentinel://sentinel1:26379,sentinel2:26379/mymaster" ) ``` -------------------------------- ### Use Cache with LLM Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/README.md Integrate the initialized cache with a LangChain LLM instance by passing it to the LLM constructor. ```python llm = LLM(cache=cache) # or LLM(cache=semantic_cache) or LLM(cache=langchain_cache) ``` -------------------------------- ### Redis Semantic Caching Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/cache.ipynb Demonstrates semantic caching using RedisSemanticCache. It initializes the cache with embeddings and a distance threshold, then compares the performance of an original query against a semantically similar one. ```python # Initialize RedisSemanticCache embeddings = OpenAIEmbeddings() semantic_cache = RedisSemanticCache( redis_url=REDIS_URL, embeddings=embeddings, distance_threshold=0.2 ) # Set the cache for LangChain to use set_llm_cache(semantic_cache) # Function to test semantic cache def test_semantic_cache(prompt): start_time = time.time() result = llm.invoke(prompt) end_time = time.time() return result, end_time - start_time # Original query original_prompt = "What is the capital of France?" result1, time1 = test_semantic_cache(original_prompt) print(f"Original query:\nPrompt: {original_prompt}\n") print(f"Result: {result1}\nTime: {time1:.2f} seconds\n") # Semantically similar query similar_prompt = "Can you tell me the capital city of France?" result2, time2 = test_semantic_cache(similar_prompt) print(f"Similar query:\nPrompt: {similar_prompt}\n") print(f"Result: {result2}\nTime: {time2:.2f} seconds\n") print(f"Speed improvement: {time1 / time2:.2f}x faster") ``` -------------------------------- ### Manual RedisCache interactions Source: https://context7.com/langchain-ai/langchain-redis/llms.txt Demonstrates manual control over the RedisCache, including updating with results, looking up entries, and checking for cache misses. ```python prompt = "What is 2 + 2?" llm_string = "openai/gpt-4o-mini" result = [Generation(text="4")] # Store a result cache.update(prompt, llm_string, result) # Retrieve a result hit = cache.lookup(prompt, llm_string) if hit: print(f"Cache hit: {hit[0].text}") # Cache hit: 4 else: print("Cache miss") # Check that a different prompt is a miss miss = cache.lookup("What is 3 + 3?", llm_string) print(miss) # None # Clear all entries with prefix "myapp:" cache.clear() ``` -------------------------------- ### Initialize RedisChatMessageHistory with Custom Configuration Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/chat_history.ipynb Initializes chat history with custom Redis settings like key prefix, time-to-live (TTL), and index name. This allows for fine-grained control over how chat data is stored and managed in Redis. ```python custom_history = RedisChatMessageHistory( session_id="user_456", redis_url=REDIS_URL, key_prefix="my_chat:", ttl=3600, # Set TTL to 1 hour index_name="chat_idx", ) custom_history.add_user_message("This is a message with custom configuration.") print("Custom History:", custom_history.messages) ``` -------------------------------- ### Update dependencies using pip Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/langchain_v1_migration.md Upgrade langchain-redis and langchain-core to their latest compatible versions using pip. ```bash pip install --upgrade langchain-redis langchain-core ``` -------------------------------- ### Create and register RedisCache for LLM responses Source: https://context7.com/langchain-ai/langchain-redis/llms.txt Initializes a RedisCache with a specified TTL and prefix, then registers it globally to automatically cache LLM responses. ```python from langchain_redis import RedisCache from langchain_core.globals import set_llm_cache from langchain_core.outputs import Generation from langchain_openai import ChatOpenAI # --- Create and register the cache --- cache = RedisCache( redis_url="redis://localhost:6379", ttl=3600, # 1 hour; None means no expiry prefix="myapp", # namespace prefix for keys ) set_llm_cache(cache) # Now every LLM call is cached automatically llm = ChatOpenAI(model="gpt-4o-mini") response1 = llm.invoke("What is the capital of France?") response2 = llm.invoke("What is the capital of France?") # served from cache ``` -------------------------------- ### Update dependencies using poetry Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/langchain_v1_migration.md Configure your pyproject.toml with the required Python and langchain-core versions, then update dependencies using poetry. ```bash # Update pyproject.toml # python = ">=3.10,<3.14" # langchain-core = "^1.0" poetry lock poetry install ``` -------------------------------- ### Configure Python Logging Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/README.md Set up Python's built-in logging module to capture INFO level messages from the package for debugging. ```python import logging logging.basicConfig(level=logging.INFO) ``` -------------------------------- ### Troubleshooting: Reinstall dependencies with updated resolver Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/langchain_v1_migration.md If dependency conflicts arise, clear the pip cache and reinstall langchain-redis and langchain-core using the --force-reinstall flag. ```bash # Clear dependency cache pip cache purge # Install with updated resolver pip install --upgrade --force-reinstall langchain-redis langchain-core ``` -------------------------------- ### Import Required Libraries for RedisVectorStore Source: https://github.com/langchain-ai/langchain-redis/blob/main/libs/redis/docs/vectorstores.ipynb Imports essential libraries for working with RedisVectorStore, including Document from langchain_core, fetch_20newsgroups from sklearn.datasets, and RedisVectorStore from langchain_redis. ```python # ruff: noqa: E501 import os from langchain_core.documents import Document from sklearn.datasets import fetch_20newsgroups from langchain_redis import RedisVectorStore ``` -------------------------------- ### RedisCache: Sentinel-backed cache Source: https://context7.com/langchain-ai/langchain-redis/llms.txt Initializes a RedisCache using a Redis Sentinel URL for high availability. ```APIDOC ## RedisCache (Sentinel-backed) ### Description Configures `RedisCache` to connect to a Redis Sentinel setup, providing automatic failover capabilities. ### Method `RedisCache( redis_url: str, # Must be a Sentinel URL format ttl: int | None = None, prefix: str | None = None, **kwargs ) ` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **redis_url** (str) - The Sentinel connection URL (e.g., "redis+sentinel://sentinel1:26379,sentinel2:26379/mymaster"). - **ttl** (int, optional) - Time-to-live in seconds for cache entries. Defaults to None. - **prefix** (str, optional) - A namespace prefix for all cache keys. ### Request Example ```python from langchain_redis import RedisCache from langchain_core.globals import set_llm_cache sentinel_cache = RedisCache( redis_url="redis+sentinel://sentinel1:26379,sentinel2:26379/mymaster", ttl=7200, ) set_llm_cache(sentinel_cache) ``` ### Response #### Success Response (200) Returns an initialized `RedisCache` instance configured for Sentinel. #### Response Example ```json { "message": "RedisCache initialized with Sentinel support successfully" } ``` ```