[Feature Request] Programmatically Getting All Parameters for API Endpoint in OpenAI-Python Module

Hello OpenAI Staff,

I’m back on the forums after an emergency break!

With all the possible parameters for each OpenAI endpoint, I’d really like the ability to get a list of all the keyword arguments programmatically through Python’s inspect module!

For example, here are all possible parameters that make up the Completions endpoint:

engine_id
prompt
max_tokens
temperature
top_p
n
stream
logprobs
echo
stop
presence_penalty
frequency_penalty
best_of
logit_bias

Instead of having to manually initialize each parameter, you could take advantage of Python’s inspect module that has functions to gather information on various objects and functions within other modules, which if implemented could provide us with the ability to return the entire list of parameters simply by calling:

inspect.signature(openai.Completion) # Could theoretically return this if implemented to work with Signature function: (engine, prompt, max_tokens, .. logit_bias) [simplified form for easy readability]

This could be useful to programmatically create each variable based on the given function rather than having to look up the OpenAI docs to confirm you did get all the parameter names correct!

Y’all actually do have a partial implementation of this already! For example, calling:

# Calling getfullargspec() on Completion function
inspect.getfullargspec(openai.Completion)

# Returns the required 'engine' parameter, but then the rest is scoped under 'kwargs' and you can't inspect any further than that
FullArgSpec(args=['self', 'engine'], varargs=None, varkw='kwargs', defaults=(None,), kwonlyargs=[], kwonlydefaults=None, annotations={'engine': typing.Optional[str]})

I specifically find this useful when I come across functions that accept a long list of parameters. By using the inspect module, I can dynamically create a dictionary in which each key is the name of the variable which cuts time on initializing each variable by hand. Any variable that is left blank is then skipped over when I iterate through the dictionary!

I’m sure there could be several more use-cases for this feature, so I figured I’d mention it here and see what everyone’s opinion on this is and see where this idea goes going forward!


EDIT:

To further add to this, there is also a way to get the parameter Object type as well by using Signature’s callable ‘annotation’ function.

For example:

inspect.signature(openai.Completion).parameters['engine'].annotation # Use annotation on 'engine' parameter to acquire type
typing.Optional[str] # String variable required for 'engine' parameter 
# NOTE: The reason why this is typing.Optional[str] and not just 'str' is because you can also pass in an 'openai.Engine' object here!

"""
Theoretically, we could inspect the 'OpenAI.Completion' function to return all parameters and their type

Parameter Name		Parameter Type
engine_id			str
prompt				Union[str,list]
max_tokens			int
temperature			float
top_p				float
n					int
stream				bool
logprobs			int
echo				bool
stop				str
presence_penalty	float
frequency_penalty	float
best_of				int
logit_bias			dict



Let's say theoretically this was implemented and we could get all possible parameters returned using the 
Signature function. This is how'd we'd take advantage of it for quickly initializing all the default parameters:
"""
Completion_API_Dict = {}
parameters = inspect.signature(openai.Completion).parameters

for parameter in parameters:
   if(parameter.default): # If parameter default exists, load value into corresponding dictionary key
         Completion_API_Dict.update({parameter.name:parameter.default})

print(Completion_API_Dict['temperature']) # Returns default value: 1


# (Theoretically) Let's ask the user to initialize each variable but ensure dynamic type checking takes place

Completion_API_Dict = {}
parameter = list(inspect.signature(openai.Completion).parameters.values())

user_input = None
is_type_correct = None
for parameter in parameters:
    if(not parameter.annotation):
        while(not is_type_correct):
               user_input = input(f"Put value for {parameter.name}:")
               try:
                    type_validated_param_value = type(parameter.annotation)(user_input)
                    Completion_API_Dict.update({parameter.name:type_validated_param_value})
                except ValueError as e:
                     print(f"Oops, this value isn't acceptable for {parameter.name}! Try again")
    else:
        Completion_API_Dict.update({parameter.name:parameter.default})

The above script snippet would dynamically create every parameter as a dictionary key from OpenAI.Completion and then ask users to enter in the corresponding value that is type-checked beforehand. This ensures nothing goes wrong during dictionary creation and has circumvented the user having to create all the variables by hand. Passing ‘Completion_API_Dict’ to the OpenAI Completion API endpoint is this simple:

openai.Completion.create(**Completion_API_Dict) # Unpack dictionary object into function as if we do openai.Completion.create(engine="ada",prompt="Hello...",...)

Thanks y’all, keep up the good work!

2 Likes

Hello,

I confess I haven’t used your suggestion but, for example, in my case, I still prefer to use functions with .json and dynamic function parameters to compose the content calls, be it short texts, long texts, or summarizations.

I create some functions in different parts of the code with all parameters and also use defaults for ranges of the parameters that generate most results in a “fixed” way.

Let’s suppose there are 32 responses to form a content, each response block, depends somehow on the parameters that I need to send, how could I save time this way? I ask to help evolve your suggestion and also because I have not been a native programmer for almost 8 years, I am a Dentist and have been programming in Python and JS for 8 months with help from Codex, Copilot and GPT-3 when I have questions.

image

This is my youngest response. The Json is dynamic and based on function and parameters. The parameters are dynamic and depend on factors and values that are validated in ^fixed^ files or a get from our API or data that is received.