Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(community): Add TTL support to UpstashRedisCache #7422

Merged
merged 1 commit into from
Dec 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/src/cache/chat_models/upstash_redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const cache = new UpstashRedisCache({
url: "UPSTASH_REDIS_REST_URL",
token: "UPSTASH_REDIS_REST_TOKEN",
},
ttl: 3600,
});

const model = new ChatOpenAI({ cache });
1 change: 1 addition & 0 deletions examples/src/cache/upstash_redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const cache = new UpstashRedisCache({
url: "UPSTASH_REDIS_REST_URL",
token: "UPSTASH_REDIS_REST_TOKEN",
},
ttl: 3600,
});

const model = new OpenAI({ cache });
21 changes: 16 additions & 5 deletions libs/langchain-community/src/caches/upstash_redis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export type UpstashRedisCacheProps = {
* An existing Upstash Redis client.
*/
client?: Redis;
/**
* Time-to-live (TTL) for cached items in seconds.
*/
ttl?: number;
};

/**
Expand All @@ -30,6 +34,7 @@ export type UpstashRedisCacheProps = {
* url: "UPSTASH_REDIS_REST_URL",
* token: "UPSTASH_REDIS_REST_TOKEN",
* },
* ttl: 3600, // Optional: Cache entries will expire after 1 hour
* });
* // Initialize the OpenAI model with Upstash Redis cache for caching responses
* const model = new ChatOpenAI({
Expand All @@ -42,9 +47,12 @@ export type UpstashRedisCacheProps = {
export class UpstashRedisCache extends BaseCache {
private redisClient: Redis;

private ttl?: number;

constructor(props: UpstashRedisCacheProps) {
super();
const { config, client } = props;
const { config, client, ttl } = props;
this.ttl = ttl;

if (client) {
this.redisClient = client;
Expand Down Expand Up @@ -84,10 +92,13 @@ export class UpstashRedisCache extends BaseCache {
public async update(prompt: string, llmKey: string, value: Generation[]) {
for (let i = 0; i < value.length; i += 1) {
const key = getCacheKey(prompt, llmKey, String(i));
await this.redisClient.set(
key,
JSON.stringify(serializeGeneration(value[i]))
);
const serializedValue = JSON.stringify(serializeGeneration(value[i]));

if (this.ttl) {
await this.redisClient.set(key, serializedValue, { ex: this.ttl });
} else {
await this.redisClient.set(key, serializedValue);
}
}
}
}
Loading