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

docs: caching middleware update #3951

Merged
merged 3 commits into from
Dec 2, 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
38 changes: 26 additions & 12 deletions content/cookbook/01-next/122-caching-middleware.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,25 @@ export const cacheMiddleware: LanguageModelV1Middleware = {
wrapGenerate: async ({ doGenerate, params }) => {
const cacheKey = JSON.stringify(params);

const cached = await redis.get(cacheKey);
const cached = (await redis.get(cacheKey)) as Awaited<
ReturnType<LanguageModelV1['doGenerate']>
> | null;

if (cached !== null) {
return cached as ReturnType<LanguageModelV1['doGenerate']>;
return {
...cached,
response: {
...cached.response,
timestamp: cached?.response?.timestamp
? new Date(cached?.response?.timestamp)
: undefined,
},
};
}

const result = await doGenerate();

redis.set(cacheKey, { ...result, response: null }); // setting response as null avoids generateText useChat error
redis.set(cacheKey, result);

return result;
},
Expand All @@ -91,23 +102,29 @@ export const cacheMiddleware: LanguageModelV1Middleware = {

// Check if the result is in the cache
const cached = await redis.get(cacheKey);

// If cached, return a simulated ReadableStream that yields the cached result
if (cached !== null) {
// If cached, return a simulated ReadableStream that yields the cached result
// Format the timestamps in the cached response
const formattedChunks = (cached as LanguageModelV1StreamPart[]).map(p => {
if (p.type === 'response-metadata' && p.timestamp) {
return { ...p, timestamp: new Date(p.timestamp) };
} else return p;
});
return {
stream: simulateReadableStream({
initialDelayInMs: 0,
chunkDelayInMs: 10,
chunks: cached as LanguageModelV1StreamPart[],
chunks: formattedChunks,
}),
rawCall: { rawPrompt: null, rawSettings: {} },
};
}

// If not cached, proceed with streaming
const { stream, rawCall, rawResponse, request, warnings } =
await doStream();
const { stream, ...rest } = await doStream();

const fullResponse: unknown[] = [];
const fullResponse: LanguageModelV1StreamPart[] = [];

const transformStream = new TransformStream<
LanguageModelV1StreamPart,
Expand All @@ -125,10 +142,7 @@ export const cacheMiddleware: LanguageModelV1Middleware = {

return {
stream: stream.pipeThrough(transformStream),
rawCall,
rawResponse,
request,
warnings,
...rest,
};
},
};
Expand Down
38 changes: 26 additions & 12 deletions content/docs/06-advanced/04-caching.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,25 @@ export const cacheMiddleware: LanguageModelV1Middleware = {
wrapGenerate: async ({ doGenerate, params }) => {
const cacheKey = JSON.stringify(params);

const cached = await redis.get(cacheKey);
const cached = (await redis.get(cacheKey)) as Awaited<
ReturnType<LanguageModelV1['doGenerate']>
> | null;

if (cached !== null) {
return cached as ReturnType<LanguageModelV1['doGenerate']>;
return {
...cached,
response: {
...cached.response,
timestamp: cached?.response?.timestamp
? new Date(cached?.response?.timestamp)
: undefined,
},
};
}

const result = await doGenerate();

redis.set(cacheKey, { ...result, response: null }); // setting response as null avoids generateText useChat error
redis.set(cacheKey, result);

return result;
},
Expand All @@ -45,23 +56,29 @@ export const cacheMiddleware: LanguageModelV1Middleware = {

// Check if the result is in the cache
const cached = await redis.get(cacheKey);

// If cached, return a simulated ReadableStream that yields the cached result
if (cached !== null) {
// If cached, return a simulated ReadableStream that yields the cached result
// Format the timestamps in the cached response
const formattedChunks = (cached as LanguageModelV1StreamPart[]).map(p => {
if (p.type === 'response-metadata' && p.timestamp) {
return { ...p, timestamp: new Date(p.timestamp) };
} else return p;
});
return {
stream: simulateReadableStream({
initialDelayInMs: 0,
chunkDelayInMs: 10,
chunks: cached as LanguageModelV1StreamPart[],
chunks: formattedChunks,
}),
rawCall: { rawPrompt: null, rawSettings: {} },
};
}

// If not cached, proceed with streaming
const { stream, rawCall, rawResponse, request, warnings } =
await doStream();
const { stream, ...rest } = await doStream();

const fullResponse: unknown[] = [];
const fullResponse: LanguageModelV1StreamPart[] = [];

const transformStream = new TransformStream<
LanguageModelV1StreamPart,
Expand All @@ -79,10 +96,7 @@ export const cacheMiddleware: LanguageModelV1Middleware = {

return {
stream: stream.pipeThrough(transformStream),
rawCall,
rawResponse,
request,
warnings,
...rest,
};
},
};
Expand Down
Loading