笔记
截至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客户端使用示例。