Semantic cache instance setup
This guide walks you through creating a Tair AI Gateway instance, configuring the semantic cache plugin, obtaining connection information, and verifying the cache with a complete example. The entire process takes about 15 minutes.
Prerequisites
-
You have an Alibaba Cloud account with real-name verification.
-
You have an existing Virtual Private Cloud (VPC) and a vSwitch in the target region. If not, create a VPC first.
Step 1: Create a Tair instance
Skip this step if you only need the model service and do not need the Tair semantic cache plugin.
The semantic cache requires a Tair instance as its storage backend. You can also skip this step if you already have a Tair memory-type cluster instance in proxy mode.
The Tair instance must be in the same region and availability zone as the Tair Semantic Cache Gateway instance that you create later. The current public-beta nodes are available in Beijing Zones I and L, Shanghai Zones E, L, and N, and Hangzhou Zones J and K.
Go to the Tair console - Instance list, click Create Instance, and configure the following parameters:
|
Parameter |
Value |
|
Product |
Enhanced Edition (Tair) |
|
Region |
Beijing, Shanghai, or Hangzhou |
|
Zone Settings |
Beijing Zone I or L, Shanghai Zone E, L, or N, or Hangzhou Zone J or K |
|
Architecture type |
Cluster |
|
Connection mode |
Proxy mode |
Free trial
During the public beta, a free trial instance with the specification Tair memory type - cluster architecture (2 shards × 1 GB) is available for 1 month after creation.
-
Go to the Alibaba Cloud Free Trial - NoSQL Database page.
-
Select Tair (Redis OSS-compatible) > Memory Type 2 GB - cluster architecture, and then click Try Now.
-
Wait for the instance to be created (about 1 to 3 minutes). In the Instance List, copy the Instance ID.
The free trial is only available for the fixed specification mentioned above. If you need higher specifications or a longer usage period, purchase an instance or renew an existing one on the Tair console. When purchasing, ensure you select Tair Enterprise Edition, Memory as the storage medium, and cluster architecture.
Step 2: Create a semantic cache gateway instance
-
Log on to the Tair Semantic Cache console. Click Create Instance.
-
Configure the following parameters:
Parameter
Recommended value
Description
Billing Method
pay-as-you-go
Free during the public beta.
Region and Zone Settings
Same as the Tair instance
Must be in the same region and availability zone.
VPC / vSwitch
Same as the Tair instance
The gateway needs to access Tair over the internal network.
Specification
Public Preview Node
Free specification for the public beta.
NoteThe semantic cache is a plugin feature of the semantic cache gateway instance. After the gateway instance is created, click the instance ID to go to the instance details page and enable it on the Plugin Management page. If you do not enable the semantic cache plugin, only the model service is available.
-
Click Buy Now.
Step 3: Configure the semantic cache plugin
Skip this step if you only need the model service, and go directly to Step 4.
-
Click the instance ID to go to the details page of the semantic cache gateway instance.
-
Click Plugin Management > Add Plugin, and select a mode based on your scenario. For first-time use, we recommend selecting OpenAI Compatible Mode.
Choose one or both modes based on your use case.
OpenAI-compatible mode (Recommended)
This mode allows you to use the cache without building your own LLM invocation pipeline. Simply replace the base URL to get started.
|
Parameter |
Default |
Description |
|
Plugin Name |
- |
User-defined. |
|
Associated Tair Instance ID/Name (Cache ID) |
- |
Required. Paste the instance ID from Step 1. |
|
Model Service |
Platform System Provider (Bailian)·Platform Managed |
The platform model service is used by default. |
|
Cache Policy |
Semantic Cache |
Semantic cache includes exact match. If you only need exact matching, change this to Precise Cache. |
|
Cache Time-to-Live (TTL) |
0 (Never expires) |
If your answers have time sensitivity, set an appropriate value in seconds. Setting a TTL is recommended. |
|
Retrieve Context |
Last Question |
Available only when Cache Policy is set to Semantic Cache. When semantic matching based on context is required, select Rewritten question. |
|
Embedding Model |
text-embedding-v4 |
Keep the default value. |
|
Similarity threshold mode |
Fixed threshold |
Available only when Cache Policy is set to Semantic Cache.
|
|
Similarity Threshold |
0.85 |
Displayed only when Similarity threshold mode is set to Fixed threshold. If there are too many false cache hits, increase the value to 0.9–0.95. If the hit rate is low, decrease it to 0.8. |
|
Maximum error rate |
0.01 |
Displayed only when Similarity threshold mode is set to Dynamic threshold. Valid values: (0, 1). A value of 0.01 roughly means that the system aims to keep incorrect answers caused by false cache hits to no more than about 1 in every 100 requests. A smaller value makes cache hit decisions more conservative. |
|
Sampling comparison strategy |
Short answer |
Displayed only when Similarity threshold mode is set to Dynamic threshold. Determines how the system checks whether a cached answer is consistent with the model answer during sampling. The system uses the results to estimate the error rate and adjust the threshold. Select a strategy based on the answer type:
|
|
Vector Cache Time-to-Live (TTL) |
0 (Never expires) |
If your answers are time-sensitive, set an appropriate value in seconds. Setting a TTL is recommended. |
|
Index Field |
model |
Optional. Used for fine-grained cache filtering. Supports one-level or two-level paths, such as |
LangCache-compatible mode
This mode is suitable for applications that already have an LLM invocation pipeline and require fine-grained control over the cache.
|
Parameter |
Default |
Description |
|
Associated Tair Instance ID/Name (Cache ID) |
- |
Required. Paste the instance ID from Step 1. |
|
Cache Policy |
hybrid cache |
This policy first attempts an exact match. If it misses, it performs a semantic match. You can change it to Semantic Cache or Precise Cache as needed. |
|
Similarity Threshold |
0.85 |
Range: 0 to 1. |
|
Embedding Model |
text-embedding-v4 |
Used for vector-based matching. |
|
Cache expiration time |
0 (Never expires) |
Unit:seconds. |
After finishing the configuration, click OK. Wait for the semantic cache plugin to be created (within about 30 seconds).
Step 4: Get connection info and set whitelist
-
On the details page of the semantic cache gateway instance, go to the Instance Information page. In the Network Access (Endpoint/Base URL) section, get the service address:
Type
Purpose
Example format
VPC
Use within the same VPC to replace the
base_urlin the OpenAI SDK.https://<your-service-address>/compatible-mode/v1Public Access
Use over the public network to replace the
base_urlin the OpenAI SDK. Disabled by default; to enable, click Request next to Public Access.https://<your-service-address>/compatible-mode/v1NoteWhen using public access, configure the IP whitelist to avoid access failures.
-
On the details page of the semantic cache gateway instance, go to the API Key page to create, manage, and view your API keys.
Step 5: Verify the setup
-
Verify that the OpenAI model service works (without the semantic cache plugin).
curl https://<your-service-address>/compatible-mode/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer <your-api-key>" \ -d '{ "model": "qwen3.7-plus", "messages": [{"role": "user", "content": "hello"}], "stream": true, "enable_thinking": false }' -
Verify that the semantic cache plugin works.
Use the following code to verify that the semantic cache plugin is working. The logic is to send two semantically similar questions. The second request should be significantly faster, indicating a cache hit.
NoteThe following sample code does not enable streaming, so the first response may take a while. Enable streaming in your own scenarios if needed.
Verify with OpenAI-compatible mode
import time
from openai import OpenAI
client = OpenAI(
base_url="https://<your_service_address>/compatible-mode/v1", # Replace with your actual service address
api_key="<your_api_key>" # Replace with your actual API key
)
# First request: a cache miss, calls the LLM (slower)
start = time.time()
resp1 = client.chat.completions.create(
model="qwen3.6-plus",
messages=[{"role": "user", "content": "What is semantic cache?"}]
)
print(f"First request latency: {time.time() - start:.2f}s")
print(f"Response: {resp1.choices[0].message.content[:100]}")
# Second request: a semantically similar question, expects a cache hit
start = time.time()
resp2 = client.chat.completions.create(
model="qwen3.6-plus",
messages=[{"role": "user", "content": "What does semantic cache mean?"}] # Semantically similar
)
print(f"\nSimilar question latency: {time.time() - start:.2f}s")
print(f"Response: {resp2.choices[0].message.content[:100]}")
Example result:
First request latency: 41.67s
Response: **Semantic Caching** is an intelligent caching technique based on the 'meaning' of a query rather than 'exact literal matching'. It is primarily used in large language model (LLM), Natural Language Processing (NLP), and search systems to reduce computational costs and token consumption.
Similar question latency: 0.17s
Response: **Semantic Caching** is an intelligent caching technique based on the 'meaning' of a query rather than 'exact literal matching'. It is primarily used in large language model (LLM), Natural Language Processing (NLP), and search systems to reduce computational costs and token consumption.
Verify with LangCache-compatible mode
In LangCache-compatible mode, you must manually insert a cache entry before you can search for and verify it. Use the following script to quickly confirm that the instance is working correctly. The script inserts a cache entry and then searches with a semantically similar question to verify a cache hit.
Before running the script, replace the BASE_URL, CACHE_ID, and API_KEY placeholders with your actual values. For details on how to obtain these values, see Step 4.
# LangCache-compatible mode - Quick verification script
# Usage: Replace the three variables below and run: python verify_langcache.py
import requests, time
BASE_URL = "https://<YOUR_BASE_URL>" # Replace with your actual service address (must include http:// or https://)
CACHE_ID = "<YOUR_CACHE_ID>" # Replace with your actual Cache ID
API_KEY = "<YOUR_API_KEY>" # Replace with your actual API key
URL = f"{BASE_URL}/v1/caches/{CACHE_ID}"
H = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
# 1. Insert a cache entry
print("1. Inserting cache entry...")
r = requests.post(f"{URL}/entries", headers=H, json={
"prompt": "What is semantic cache?",
"response": "Semantic cache is a caching technique based on semantic similarity matching. It vectorizes "
"user requests, searches the cache for semantically similar historical requests, and reuses "
"their responses to avoid repetitive calls to a large language model, reducing cost and latency."
})
print(f" Status: {r.status_code} | Response: {r.text}")
# Wait for the index to be built
time.sleep(3)
# 2. Perform a semantic search
print("2. Performing semantic search...")
r = requests.post(f"{URL}/entries/search", headers=H, json={
"prompt": "What does semantic cache mean?",
"searchStrategies": ["exact", "semantic"]
})
print(f" Status: {r.status_code} | Response: {r.text}")
# 3. Check the result
if r.status_code == 200 and r.json().get("data"):
print("\nVerification successful: The LangCache instance is working correctly.")
else:
print("\nVerification failed: Check your configuration or refer to the error codes.")
After running the script, a non-empty data field in the search response indicates a successful semantic match and confirms that the LangCache instance is working correctly.
For the complete API specification and more operations, such as setting a TTL, clearing the cache, and filtering by attributes, see the LangCache-Compatible Mode API reference.
Next steps
-
Adjust the similarity threshold to optimize the hit rate. A lower threshold increases the hit rate but may reduce precision, while a higher threshold increases precision but may lower the hit rate.
-
Use dynamic threshold mode to reduce tuning effort (OpenAI-compatible mode only). You only need to set the maximum error rate that your business can tolerate, and the system adjusts the similarity threshold automatically. A smaller maximum error rate makes cache hit decisions more conservative.
-
Configure a Time-to-Live (TTL) to manage cache freshness. For use cases where answers can become outdated, set an appropriate expiration time.
-
Explore the full API capabilities in the Technical Architecture and API Reference.