筆記
截至2024年10月,OpenAI現在正式支持大多數型號的提示:https://openai.com/index/api-prompt-caching/。建議您改用OpenAI的官方實施。
OpenAI API的基本緩存代理,可作為CloudFlare工人部署。
這可以通過返回重複請求的緩存響應來幫助您降低OpenAI成本(並獲得更快的結果)。
代理服務器以每次要求為基礎指定緩存TTL,因此您可以根據自己的需求進行配置。例如, text-davinci-003型號為10倍,是text-curie-001的成本,因此您可以選擇為Davinci的更長的緩存結果。
客戶端兼容性:
它只有緩存帶有JSON請求主體的POST請求,因為這些請求往往是最慢的,並且是唯一要花錢的請求(目前)。
克隆回購併安裝依賴項。
您將需要註冊兩個服務(兩者都有免費層):
最後,根據wrangler.toml中的說明來設置您的Redis秘密。
根據您的使用情況,您可以嘗試用CloudFlare KV代替Redis,這最終是一致的,但可能會提供更好的閱讀延遲。檢查wrangler.toml的設置說明。
從http:// localhost:8787啟動代理服務器:
yarn start
然後,在您擁有OpenAI/OpenAi節點配置的單獨項目中,通過新的basePath傳遞,以便通過您的代理髮送請求,而不是直接發送到OpenAi:
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
+ // Point this to your local instance or Cloudflare deployment:
+ basePath: 'http://localhost:8787/proxy',
});
const openai = new OpenAIApi(configuration);然後,您可以嘗試一些示例請求。由於尚未為此保存緩存的響應,因此第一個將被代理到OpenAI,但是第二個重複/重複請求將返回緩存結果。
const options = { model : 'text-ada-001' , prompt : 'write a poem about computers' } ;
// This first request will be proxied as-is to OpenAI API, since a cached
// response does not yet exist for it:
const completion = await openai . createCompletion ( options ) ;
console . log ( 'completion:' , completion ) ;
// This second request uses the same options, so it returns nearly instantly from
// local cache and does not make a request to OpenAI:
const completionCached = await openai . createCompletion ( options ) ;
console . log ( 'completionCached:' , completionCached ) ;如果您不想無限期地緩存結果,或者您沒有在REDIS實例上設置驅逐策略,則可以使用X-Proxy-TTL標頭在幾秒鐘內指定TTL。
const configuration = new Configuration({
...
+ baseOptions: {
+ // In this example, we specify a cache TTL of 24 hours before it expires:
+ headers: { 'X-Proxy-TTL': 60 * 60 * 24 }
+ }
});如果您需要強制刷新緩存,則可以使用標題X-Proxy-Refresh 。這將從Openai獲得新的響應,並緩存此新響應。
const configuration = new Configuration({
...
+ baseOptions: {
+ headers: { 'X-Proxy-Refresh': 'true' }
+ }
});有關如何與OpenAI客戶訪問此代理的完整示例,請參見/examples/目錄。
這同時包括Node.js,Python和Ruby客戶端使用示例。