Proper encapsulation of the API keys
Describe the feature or improvement you're requesting
In the Node.js API we have the API accepting keys upon creation of the OpenAIApi object:
import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
organization: "org-1qRDHAPS0UN4vVhAii7VYY7y",
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
In Python, however, the key is set globally, which poses a problem when dealing with multiple keys/organizations in requests. It would be nice to have proper encapsulation of the key into a Python class that is responsible for the API like it is usually done for many Python APIs, instead of using global objects for keys.
Additional context
No response
Yes, I found the same problem,so how to create openai object in python?
It looks like this might just be an issue with the documentation.
I dug into the code, and many methods will take api_key and organization arguments. For example, for the completion acreate() method (and create() looks the same in the code), adding an api_key named argument -- without ever setting openai.api_key -- seems to work fine.
e.g.
openai.Completion.acreate(
api_key="your key goes here",
model="text-davinci-003",
prompt="Why did the chicken cross the road?"
)
I've only looked at the code for completions, and that's all I've tested, but I think the same will apply to most if not all methods that create and send requests.
I think there are lots of things in the library that the documentation doesn't publicize. Of course, that means this functionality (allowing api_key arguments) may be subject to change without warning... But it seems simple enough and useful enough that it wouldn't go away randomly.
According to this response, there is a non-documented feature: Many API features accept named arguments such as:
import openai
openai.ChatCompletion.create(model=gpt_model_config.model_engine,
api_key=SECRET
api_base=BASE,
api_type=TYPE,
api_version=VERSION,
...)
Fully support this. Using global state for setting keys / properties is usually not the way to go, and the possibility of creating an instance of the openai service/module would make it much easier to mock during tests. It would also help isolate usage if one is using more than one api key / api base in your app.
Great news – this is resolved in our new, fully rewritten v1.0.0 library, now in beta:
from openai import OpenAI
client = OpenAI(
api_key=os.environ['OPENAI_API_KEY'], # this is also the default, it can be omitted
)
client.chat.completions.create()
Please give it a try, and share feedback (big or small) in the linked discussion! (Not in this thread).