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

fetch.ts 1.9 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
  1. import fetch from 'node-fetch';
  2. import { ProxyAgent } from 'proxy-agent';
  3. import type { RequestInfo, RequestInit, Response } from 'node-fetch';
  4. export async function fetchWithProxy(
  5. url: RequestInfo,
  6. options: RequestInit = {},
  7. ): Promise<Response> {
  8. options.agent = new ProxyAgent();
  9. return fetch(url, options);
  10. }
  11. export function fetchWithTimeout(
  12. url: RequestInfo,
  13. options: RequestInit = {},
  14. timeout: number,
  15. ): Promise<Response> {
  16. return new Promise((resolve, reject) => {
  17. const controller = new AbortController();
  18. const { signal } = controller;
  19. options.signal = signal;
  20. const timeoutId = setTimeout(() => {
  21. controller.abort();
  22. reject(new Error(`Request timed out after ${timeout} ms`));
  23. }, timeout);
  24. fetchWithProxy(url, options)
  25. .then((response) => {
  26. clearTimeout(timeoutId);
  27. resolve(response);
  28. })
  29. .catch((error) => {
  30. clearTimeout(timeoutId);
  31. reject(error);
  32. });
  33. });
  34. }
  35. export async function fetchWithRetries(
  36. url: RequestInfo,
  37. options: RequestInit = {},
  38. timeout: number,
  39. retries: number = 4,
  40. ): Promise<Response> {
  41. let lastError;
  42. const backoff = process.env.PROMPTFOO_REQUEST_BACKOFF_MS
  43. ? parseInt(process.env.PROMPTFOO_REQUEST_BACKOFF_MS, 10)
  44. : 5000;
  45. for (let i = 0; i < retries; i++) {
  46. try {
  47. const response = await fetchWithTimeout(url, options, timeout);
  48. if (process.env.PROMPTFOO_RETRY_5XX && response.status / 100 === 5) {
  49. throw new Error(`Internal Server Error: ${response.status} ${response.statusText}`);
  50. }
  51. return response;
  52. } catch (error) {
  53. lastError = error;
  54. const waitTime = Math.pow(2, i) * (backoff + 1000 * Math.random());
  55. await new Promise((resolve) => setTimeout(resolve, waitTime));
  56. }
  57. }
  58. throw new Error(`Request failed after ${retries} retries: ${(lastError as Error).message}`);
  59. }
Tip!

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

Comments

Loading...