@jeromeetienne/openai-cache 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +43 -0
- package/dist/openai_cache.d.ts +38 -0
- package/dist/openai_cache.js +121 -0
- package/package.json +69 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jerome Etienne
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Cache OpenAI
|
|
2
|
+
This is a simple caching layer for OpenAI API requests using local file storage.
|
|
3
|
+
It helps to reduce redundant API calls by storing responses in a cache directory `./.openai_cache`.
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import OpenAI from "openai";
|
|
9
|
+
import { OpenAICache } from "./src/openai_cache"; // for repo-local usage
|
|
10
|
+
// If published to npm, replace with your package import.
|
|
11
|
+
|
|
12
|
+
const openaiCache = new OpenAICache({
|
|
13
|
+
cacheDir: ".cache/openai",
|
|
14
|
+
debug: true,
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
const client = new OpenAI({
|
|
18
|
+
apiKey: process.env.OPENAI_API_KEY,
|
|
19
|
+
fetch: openaiCache.getFetchFn(),
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
const response = await client.responses.create({
|
|
23
|
+
model: "gpt-4.1-mini",
|
|
24
|
+
input: "Say hello in one short sentence.",
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
console.log(response.output_text);
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## PRO/CON
|
|
31
|
+
- **PRO**: Reduces redundant API calls, saving time and costs.
|
|
32
|
+
data.
|
|
33
|
+
- **NOTE**: When `temperature === 0`, caching works optimally as responses are deterministic. However, with `temperature > 0`, caching may reduce variety across multiple calls since identical prompts will return cached results instead of generating new varied responses.
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
## Possible improvements
|
|
37
|
+
- dont cache if temporature > 0 or top_p < 1, You’ll freeze randomness if cached
|
|
38
|
+
- implement with keyv https://keyv.org/, instead of custom file system
|
|
39
|
+
- various storage backends (filesystem, redis, etc)
|
|
40
|
+
- built in TTL support
|
|
41
|
+
- check errors, and dont cache if error
|
|
42
|
+
- 429/500 errors should not be cached, but other errors (like invalid request) could be cached to prevent repeated bad requests
|
|
43
|
+
- tools requests errors should not be cached
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { RequestInfo } from "openai/internal/builtin-types";
|
|
2
|
+
import { Cacheable } from "cacheable";
|
|
3
|
+
/**
|
|
4
|
+
* OpenAICachingCacheable is a wrapper around the Fetch API that adds caching capabilities for OpenAI requests.
|
|
5
|
+
* It uses a Cacheable instance to store and retrieve cached responses based on a hash of the request details.
|
|
6
|
+
*/
|
|
7
|
+
export default class OpenAICache {
|
|
8
|
+
private readonly _cache;
|
|
9
|
+
constructor(cache?: Cacheable);
|
|
10
|
+
/**
|
|
11
|
+
* Cleans the OpenAI cache by deleting all cached values.
|
|
12
|
+
*/
|
|
13
|
+
cleanCache(): Promise<void>;
|
|
14
|
+
/**
|
|
15
|
+
* return a fetch function that can be passed to OpenAI client for caching support
|
|
16
|
+
*
|
|
17
|
+
* ```js
|
|
18
|
+
* const openai = new OpenAI({
|
|
19
|
+
* fetch: openaiCache.getFetchFn()
|
|
20
|
+
* });
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
getFetchFn(): (input: RequestInfo, init?: RequestInit) => Promise<Response>;
|
|
24
|
+
/**
|
|
25
|
+
* This is the fetch() implementation that adds caching for OpenAI requests.
|
|
26
|
+
*
|
|
27
|
+
* @param input The resource that you wish to fetch.
|
|
28
|
+
* @param init An options object containing any custom settings that you want to apply to the request.
|
|
29
|
+
* @returns A Promise that resolves to the Response to that request.
|
|
30
|
+
*/
|
|
31
|
+
private _fetch;
|
|
32
|
+
/**
|
|
33
|
+
* Remove transfer/content encodings that no longer apply once the body is materialized
|
|
34
|
+
* and optionally set a correct content-length for the cached payload.
|
|
35
|
+
*/
|
|
36
|
+
private static _normalizeHeaders;
|
|
37
|
+
private static _serializeBodyForHash;
|
|
38
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
// node imports
|
|
7
|
+
const node_crypto_1 = __importDefault(require("node:crypto"));
|
|
8
|
+
const node_buffer_1 = require("node:buffer");
|
|
9
|
+
const cacheable_1 = require("cacheable");
|
|
10
|
+
/**
|
|
11
|
+
* OpenAICachingCacheable is a wrapper around the Fetch API that adds caching capabilities for OpenAI requests.
|
|
12
|
+
* It uses a Cacheable instance to store and retrieve cached responses based on a hash of the request details.
|
|
13
|
+
*/
|
|
14
|
+
class OpenAICache {
|
|
15
|
+
constructor(cache) {
|
|
16
|
+
this._cache = cache !== null && cache !== void 0 ? cache : new cacheable_1.Cacheable();
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Cleans the OpenAI cache by deleting all cached values.
|
|
20
|
+
*/
|
|
21
|
+
async cleanCache() {
|
|
22
|
+
await this._cache.clear();
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* return a fetch function that can be passed to OpenAI client for caching support
|
|
26
|
+
*
|
|
27
|
+
* ```js
|
|
28
|
+
* const openai = new OpenAI({
|
|
29
|
+
* fetch: openaiCache.getFetchFn()
|
|
30
|
+
* });
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
getFetchFn() {
|
|
34
|
+
return this._fetch.bind(this);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* This is the fetch() implementation that adds caching for OpenAI requests.
|
|
38
|
+
*
|
|
39
|
+
* @param input The resource that you wish to fetch.
|
|
40
|
+
* @param init An options object containing any custom settings that you want to apply to the request.
|
|
41
|
+
* @returns A Promise that resolves to the Response to that request.
|
|
42
|
+
*/
|
|
43
|
+
async _fetch(input, init) {
|
|
44
|
+
var _a;
|
|
45
|
+
// Extract the URL from the input (string or Request)
|
|
46
|
+
const url = typeof input === "string" ? input : input instanceof Request ? input.url : input.toString();
|
|
47
|
+
// Normalize HTTP method
|
|
48
|
+
const method = ((init === null || init === void 0 ? void 0 : init.method) || "GET").toUpperCase();
|
|
49
|
+
// Generate body hash payload
|
|
50
|
+
const bodyForHash = OpenAICache._serializeBodyForHash(init === null || init === void 0 ? void 0 : init.body);
|
|
51
|
+
// If body type unsupported, skip caching
|
|
52
|
+
if (bodyForHash === null)
|
|
53
|
+
return fetch(input, init);
|
|
54
|
+
// Build cache key and file path
|
|
55
|
+
const cacheKey = node_crypto_1.default.createHash("sha256")
|
|
56
|
+
.update(`${method}:${url}:${bodyForHash}`)
|
|
57
|
+
.digest("hex");
|
|
58
|
+
const cached = (await this._cache.get(cacheKey));
|
|
59
|
+
if (cached !== undefined) {
|
|
60
|
+
const bodyEncoding = (_a = cached.bodyEncoding) !== null && _a !== void 0 ? _a : "utf8";
|
|
61
|
+
const cachedBody = node_buffer_1.Buffer.from(cached.body, bodyEncoding);
|
|
62
|
+
// Return cached response
|
|
63
|
+
return new Response(cachedBody, {
|
|
64
|
+
status: cached.status,
|
|
65
|
+
headers: cached.headers,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
// Perform network fetch
|
|
69
|
+
const response = await fetch(input, init);
|
|
70
|
+
const clonedResponse = response.clone();
|
|
71
|
+
// Materialize response body for caching
|
|
72
|
+
const responseBuffer = node_buffer_1.Buffer.from(await clonedResponse.arrayBuffer());
|
|
73
|
+
// Collect headers and normalize them
|
|
74
|
+
const headers = Array.from(clonedResponse.headers.entries());
|
|
75
|
+
const normalizedHeaders = OpenAICache._normalizeHeaders(headers, responseBuffer.length);
|
|
76
|
+
await this._cache.set(cacheKey, {
|
|
77
|
+
status: clonedResponse.status,
|
|
78
|
+
headers: normalizedHeaders,
|
|
79
|
+
body: responseBuffer.toString("base64"),
|
|
80
|
+
bodyEncoding: "base64",
|
|
81
|
+
});
|
|
82
|
+
// Return live response (body already buffered)
|
|
83
|
+
return new Response(responseBuffer, { status: response.status, headers: normalizedHeaders });
|
|
84
|
+
}
|
|
85
|
+
///////////////////////////////////////////////////////////////////////////////
|
|
86
|
+
///////////////////////////////////////////////////////////////////////////////
|
|
87
|
+
// Private functions
|
|
88
|
+
///////////////////////////////////////////////////////////////////////////////
|
|
89
|
+
///////////////////////////////////////////////////////////////////////////////
|
|
90
|
+
/**
|
|
91
|
+
* Remove transfer/content encodings that no longer apply once the body is materialized
|
|
92
|
+
* and optionally set a correct content-length for the cached payload.
|
|
93
|
+
*/
|
|
94
|
+
static _normalizeHeaders(headers, bodyLength) {
|
|
95
|
+
const drop = new Set([
|
|
96
|
+
"content-encoding", // body is already decoded by fetch()
|
|
97
|
+
"transfer-encoding",
|
|
98
|
+
"content-length", // will be recalculated
|
|
99
|
+
]);
|
|
100
|
+
const filtered = headers.filter(([name]) => drop.has(name.toLowerCase()) === false);
|
|
101
|
+
if (bodyLength !== undefined) {
|
|
102
|
+
filtered.push(["content-length", String(bodyLength)]);
|
|
103
|
+
}
|
|
104
|
+
return filtered;
|
|
105
|
+
}
|
|
106
|
+
// Serialize body into a deterministic string for hashing
|
|
107
|
+
static _serializeBodyForHash(body) {
|
|
108
|
+
if (body === undefined || body === null)
|
|
109
|
+
return "";
|
|
110
|
+
if (typeof body === "string")
|
|
111
|
+
return body;
|
|
112
|
+
if (node_buffer_1.Buffer.isBuffer(body))
|
|
113
|
+
return body.toString("base64");
|
|
114
|
+
if (body instanceof ArrayBuffer)
|
|
115
|
+
return node_buffer_1.Buffer.from(body).toString("base64");
|
|
116
|
+
if (ArrayBuffer.isView(body))
|
|
117
|
+
return node_buffer_1.Buffer.from(body.buffer, body.byteOffset, body.byteLength).toString("base64");
|
|
118
|
+
return null; // unsupported body type
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
exports.default = OpenAICache;
|
package/package.json
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@jeromeetienne/openai-cache",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"main": "dist/openai_cache.js",
|
|
5
|
+
"types": "dist/openai_cache.d.ts",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/openai_cache.d.ts",
|
|
9
|
+
"default": "./dist/openai_cache.js"
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
"files": [
|
|
13
|
+
"dist",
|
|
14
|
+
"README.md",
|
|
15
|
+
"LICENSE"
|
|
16
|
+
],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"example:openai_cache": "tsx examples/openai_cache_example.ts",
|
|
19
|
+
"example:tts": "tsx examples/tts_example.ts",
|
|
20
|
+
"example:image_generation": "tsx examples/image_generation_example.ts",
|
|
21
|
+
"example:image_understanding": "tsx examples/image_understanding_example.ts",
|
|
22
|
+
"clean_cache": "rm -f ./examples/.openai_cache.sqlite",
|
|
23
|
+
"build": "tsc -p tsconfig.json",
|
|
24
|
+
"clean": "rm -rf dist",
|
|
25
|
+
"prepublishOnly": "npm run test && npm run build",
|
|
26
|
+
"test": "tsx --test ./test/*_test.ts",
|
|
27
|
+
"test:watch": "tsx --test --watch ./test/*_test.ts",
|
|
28
|
+
"version:patch": "npm version patch",
|
|
29
|
+
"version:minor": "npm version minor",
|
|
30
|
+
"version:major": "npm version major",
|
|
31
|
+
"version:prerelease": "npm version prerelease --preid=rc"
|
|
32
|
+
},
|
|
33
|
+
"keywords": [
|
|
34
|
+
"openai",
|
|
35
|
+
"cache",
|
|
36
|
+
"caching",
|
|
37
|
+
"keyv",
|
|
38
|
+
"sqlite",
|
|
39
|
+
"typescript"
|
|
40
|
+
],
|
|
41
|
+
"author": "jerome etienne <jerome.etienne@example.com>",
|
|
42
|
+
"license": "MIT",
|
|
43
|
+
"description": "A caching layer for OpenAI API calls, designed to improve performance and reduce costs.",
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/jeromeetienne/democracy.ai.git",
|
|
50
|
+
"directory": "packages/openai_cache"
|
|
51
|
+
},
|
|
52
|
+
"homepage": "https://github.com/jeromeetienne/democracy.ai/tree/main/packages/openai_cache",
|
|
53
|
+
"bugs": {
|
|
54
|
+
"url": "https://github.com/jeromeetienne/democracy.ai/issues"
|
|
55
|
+
},
|
|
56
|
+
"devDependencies": {
|
|
57
|
+
"@keyv/sqlite": "^4.0.8",
|
|
58
|
+
"@types/node": "^25.1.0",
|
|
59
|
+
"keyv": "^5.6.0",
|
|
60
|
+
"openai": "^6.17.0",
|
|
61
|
+
"ts-node": "^10.9.2",
|
|
62
|
+
"tsx": "^4.21.0",
|
|
63
|
+
"typescript": "^5.9.3",
|
|
64
|
+
"zod": "^4.3.6"
|
|
65
|
+
},
|
|
66
|
+
"dependencies": {
|
|
67
|
+
"cacheable": "^2.3.3"
|
|
68
|
+
}
|
|
69
|
+
}
|