Package: openai-wrapi
OpenAI Proxy [openai-wrapi]A drop-in wrapper to theopenaipackage that tracks costs per user, project, model and staging account.Problem statementOpenAI does not currently provide any way to monitor or limit API usage costs by user*, project or model. In fact, there is no concept of "project", only users (which correspond to email addresses), organizations (which correspond to OpenAI accounts and must be individually funded) and API keys (which can be used interchangeably across any organizations to which a user belongs).This leads to a proliferation of API keys and users opening up a wider attack surface from a security point of view. Furthermore, users cannot be forced to use MFA and may continue to use the API and create API keys, even if their email no longer exists.Lastly, it is easy to make redundant calls to the API incurring unnecessary costs, especially when developing in an interactive environment such as a Jupyter notebook.* The latest version of the OpenAI usage dashboard shows number of calls per user, but not cost.SolutionThis repo provides a wrapper which checks usage limits before passing on the request to the OpenAI API and records the usage costs per user, project, model and staging account. It leverages the IAM permission framework of AWS to control access to the OpenAI API, without exposing the unique API keys per staging account. Responses from the OpenAI API are cached by default. Infrastructure As Code (IAC) is given to deploy the solution using a serverless architecture in AWS at a minimal extra cost and latency.InstallFrom PyPI (for users)pipinstallopenai-wrapiFrom source (for admins)gitclonehttps://github.com/teticio/openai-proxy.gitcdopenai-proxy
pipinstall.DeployIdeally, you should have one OpenAI account per staging account (dev, prod). Create aterraform.tfvarsfile in theiacdirectory with the following variables:profile="default"# AWS profile to useregion="eu-west-2"# AWS region to deploy tonum_azs=3# Number of availability zones to deploy to (limited by available Elastic IP addresses)use_elasticache=true# Whether to use ElastiCache Memcachestages={# Staging accounts"dev"={openai_api_key="sk-XXX"openai_org_id="org-XXX"}"prod"={openai_api_key="sk-YYY"openai_org_id="org-YYY"}}To deploy run:cdiac
terraforminit
terraformapply-auto-approveThis will createA streaming Lambda function URL to proxy calls to the OpenAI API per staging account (dev, prod).A Lambda function to set usage limits and flush the cache per staging account (dev, prod).A DynamoDB table to store usage and limits.An optional ElastiCache Memcached cluster to cache OpenAI API responses.UsageIn order to use the proxy in your Python code, provided you have the appropriate IAM permissions, includeimportopenai_wrapiasopenaiYou no longer need set your OpenAI API key or organization ID as these are securely stored in the corresponding Lambda functions. Instead, you should set yourOPENAI_API_KEYenvironment variable to besk-XXX, whereXXXcorresponds to the URLhttps://XXX.lambda-url.region.on.aws/of your Lambda function, as output by Terraform.If you plan to use packages such aslangchainwhich use theopenaipackage internally, you need only ensure you have previously importedopenai_wrapi.By default, the project associated with any API calls will beN/A. In order to set the project name:openai.set_project("my-project")To set the staging account:openai.set_staging("dev")If you want to disable caching (enabled by default):openai.set_caching(False)Alternatively, if you are using version 1.x.x ofopenai, you can create a client usingclient=openai.OpenAI(project="my-project",staging="dev",caching=True)It is also possible to set these parameters using environment variables:os.environ["OPENAI_DEFAULT_PROJECT"]="hello"os.environ["OPENAI_DEFAULT_STAGING"]="dev"os.environ["OPENAI_DEFAULT_CACHING"]="0"(Note that it is necessary to do this when usinglangchainwith version 1.x.x ofopenai, which explicitly creates a new OpenAI client.)If you want to use the proxy from somewhere other than Python, you can use the URL of the Lambda function in place of the OpenAI endpoint, provided you authenticate with AWS appropriately. In fact, you can even make the Lambda function URL public and restrict the access with CORS, so that it can be used directly in a frontend application.AdminsAgain, supposing you have the IAM permissions to be able to invoke theopenai-admin-{staging}Lambda function, you canset the usage limits per user, project and model:openai.set_limits(limit=10,# 10 USDstaging="dev",# Dev accountproject="my-project",# Project nameuser="me",# Optionalmodel="gpt-4",# Optional)flush the cache:openai.flush_cache(staging="dev")The prices for the OpenAI models can be set in theiac/openai_proxy/prices.jsfile.Note that this wrapper currently works for major versions 0 and 1 of theopenaipackage.To see the usage in a dashboard, runstreamlitrunapp.py