Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

cache.ts 3.7 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
  1. import fs from 'fs';
  2. import path from 'path';
  3. import cacheManager from 'cache-manager';
  4. import fsStore from 'cache-manager-fs-hash';
  5. import logger from './logger';
  6. import { fetchWithRetries } from './fetch';
  7. import { getConfigDirectoryPath } from './util';
  8. import type { Cache } from 'cache-manager';
  9. import type { RequestInfo, RequestInit } from 'node-fetch';
  10. let cacheInstance: Cache | undefined;
  11. let enabled =
  12. typeof process.env.PROMPTFOO_CACHE_ENABLED === 'undefined'
  13. ? true
  14. : process.env.PROMPTFOO_CACHE_ENABLED === '1' ||
  15. process.env.PROMPTFOO_CACHE_ENABLED === 'true' ||
  16. process.env.PROMPTFOO_CACHE_ENABLED === 'yes';
  17. let cacheType =
  18. process.env.PROMPTFOO_CACHE_TYPE || (process.env.NODE_ENV === 'test' ? 'memory' : 'disk');
  19. export function getCache() {
  20. if (!cacheInstance) {
  21. let cachePath = '';
  22. if (cacheType === 'disk' && enabled) {
  23. cachePath = process.env.PROMPTFOO_CACHE_PATH || path.join(getConfigDirectoryPath(), 'cache');
  24. if (!fs.existsSync(cachePath)) {
  25. logger.info(`Creating cache folder at ${cachePath}.`);
  26. fs.mkdirSync(cachePath, { recursive: true });
  27. }
  28. }
  29. cacheInstance = cacheManager.caching({
  30. store: cacheType === 'disk' && enabled ? fsStore : 'memory',
  31. options: {
  32. max: process.env.PROMPTFOO_CACHE_MAX_FILE_COUNT || 10_000, // number of files
  33. path: cachePath,
  34. ttl: process.env.PROMPTFOO_CACHE_TTL || 60 * 60 * 24 * 14, // in seconds, 14 days
  35. maxsize: process.env.PROMPTFOO_CACHE_MAX_SIZE || 1e7, // in bytes, 10mb
  36. //zip: true, // whether to use gzip compression
  37. },
  38. });
  39. }
  40. return cacheInstance;
  41. }
  42. export async function fetchWithCache(
  43. url: RequestInfo,
  44. options: RequestInit = {},
  45. timeout: number,
  46. format: 'json' | 'text' = 'json',
  47. bust: boolean = false,
  48. ): Promise<{ data: any; cached: boolean }> {
  49. if (!enabled || bust) {
  50. const resp = await fetchWithRetries(url, options, timeout);
  51. const respText = await resp.text();
  52. try {
  53. return {
  54. cached: false,
  55. data: format === 'json' ? JSON.parse(respText) : respText,
  56. };
  57. } catch (error) {
  58. throw new Error(`Error parsing response as JSON: ${respText}`);
  59. }
  60. }
  61. const cache = await getCache();
  62. const copy = Object.assign({}, options);
  63. delete copy.headers;
  64. const cacheKey = `fetch:${url}:${JSON.stringify(copy)}`;
  65. let cached = true;
  66. let errorResponse = null;
  67. // Use wrap to ensure that the fetch is only done once even for concurrent invocations
  68. const cachedResponse = await cache.wrap(cacheKey, async () => {
  69. // Fetch the actual data and store it in the cache
  70. cached = false;
  71. const response = await fetchWithRetries(url, options, timeout);
  72. const responseText = await response.text();
  73. try {
  74. const data = JSON.stringify(format === 'json' ? JSON.parse(responseText) : responseText);
  75. if (!response.ok) {
  76. errorResponse = data;
  77. // Don't cache error responses
  78. return;
  79. }
  80. if (!data) {
  81. // Don't cache empty responses
  82. return;
  83. }
  84. logger.debug(`Storing ${url} response in cache: ${data}`);
  85. return data;
  86. } catch (err) {
  87. throw new Error(
  88. `Error parsing response from ${url}: ${
  89. (err as Error).message
  90. }. Received text: ${responseText}`,
  91. );
  92. }
  93. });
  94. if (cached && cachedResponse) {
  95. logger.debug(`Returning cached response for ${url}: ${cachedResponse}`);
  96. }
  97. return {
  98. cached,
  99. data: JSON.parse((cachedResponse ?? errorResponse) as string),
  100. };
  101. }
  102. export function enableCache() {
  103. enabled = true;
  104. }
  105. export function disableCache() {
  106. enabled = false;
  107. }
  108. export async function clearCache() {
  109. return getCache().reset();
  110. }
  111. export function isCacheEnabled() {
  112. return enabled;
  113. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...