Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 10 additions & 11 deletions openai/api_requestor.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def _build_api_url(url, query):
scheme, netloc, path, base_query, fragment = urlsplit(url)

if base_query:
query = "%s&%s" % (base_query, query)
query = f"{base_query}&{query}"
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _build_api_url refactored with the following changes:


return urlunsplit((scheme, netloc, path, query, fragment))

Expand All @@ -48,8 +48,7 @@ def _make_session() -> requests.Session:
if not openai.verify_ssl_certs:
warnings.warn("verify_ssl_certs is ignored; openai always verifies.")
s = requests.Session()
proxies = _requests_proxies_arg(openai.proxy)
if proxies:
if proxies := _requests_proxies_arg(openai.proxy):
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function _make_session refactored with the following changes:

s.proxies = proxies
s.mount(
"https://",
Expand Down Expand Up @@ -95,9 +94,9 @@ def __init__(
def format_app_info(cls, info):
str = info["name"]
if info["version"]:
str += "/%s" % (info["version"],)
str += f'/{info["version"]}'
if info["url"]:
str += " (%s)" % (info["url"],)
str += f' ({info["url"]})'
Comment on lines -98 to +99
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function APIRequestor.format_app_info refactored with the following changes:

return str

@overload
Expand Down Expand Up @@ -249,9 +248,9 @@ def handle_error_response(self, rbody, rcode, resp, rheaders, stream_error=False
def request_headers(
self, method: str, extra, request_id: Optional[str]
) -> Dict[str, str]:
user_agent = "OpenAI/v1 PythonBindings/%s" % (version.VERSION,)
user_agent = f"OpenAI/v1 PythonBindings/{version.VERSION}"
if openai.app_info:
user_agent += " " + self.format_app_info(openai.app_info)
user_agent += f" {self.format_app_info(openai.app_info)}"
Comment on lines -252 to +253
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function APIRequestor.request_headers refactored with the following changes:


uname_without_node = " ".join(
v for k, v in platform.uname()._asdict().items() if k != "node"
Expand All @@ -273,7 +272,7 @@ def request_headers(
"User-Agent": user_agent,
}

headers.update(util.api_key_to_header(self.api_type, self.api_key))
headers |= util.api_key_to_header(self.api_type, self.api_key)

if self.organization:
headers["OpenAI-Organization"] = self.organization
Expand Down Expand Up @@ -322,11 +321,11 @@ def request_raw(
request_id: Optional[str] = None,
request_timeout: Optional[Union[float, Tuple[float, float]]] = None,
) -> requests.Response:
abs_url = "%s%s" % (self.api_base, url)
abs_url = f"{self.api_base}{url}"
headers = self._validate_headers(supplied_headers)

data = None
if method == "get" or method == "delete":
if method in ["get", "delete"]:
Comment on lines -325 to +328
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function APIRequestor.request_raw refactored with the following changes:

if params:
encoded_params = urlencode(
[(k, v) for k, v in params.items() if v is not None]
Expand Down Expand Up @@ -360,7 +359,7 @@ def request_raw(
data=data,
files=files,
stream=stream,
timeout=request_timeout if request_timeout else TIMEOUT_SECS,
timeout=request_timeout or TIMEOUT_SECS,
)
except requests.exceptions.Timeout as e:
raise error.Timeout("Request timed out") from e
Expand Down
23 changes: 5 additions & 18 deletions openai/api_resources/abstract/api_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,7 @@ def class_url(cls):
# Namespaces are separated in object names with periods (.) and in URLs
# with forward slashes (/), so replace the former with the latter.
base = cls.OBJECT_NAME.replace(".", "/") # type: ignore
if cls.api_prefix:
return "/%s/%s" % (cls.api_prefix, base)
return "/%s" % (base)
return f"/{cls.api_prefix}/{base}" if cls.api_prefix else f"/{base}"
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function APIResource.class_url refactored with the following changes:


def instance_url(self, operation=None):
id = self.get("id")
Expand All @@ -65,27 +63,16 @@ def instance_url(self, operation=None):

if not operation:
base = self.class_url()
return "/%s%s/%s?api-version=%s" % (
self.azure_api_prefix,
base,
extn,
api_version,
)
return f"/{self.azure_api_prefix}{base}/{extn}?api-version={api_version}"

return "/%s/%s/%s/%s?api-version=%s" % (
self.azure_api_prefix,
self.azure_deployments_prefix,
extn,
operation,
api_version,
)
return f"/{self.azure_api_prefix}/{self.azure_deployments_prefix}/{extn}/{operation}?api-version={api_version}"

elif self.typed_api_type == ApiType.OPEN_AI:
base = self.class_url()
return "%s/%s" % (base, extn)
return f"{base}/{extn}"

else:
raise error.InvalidAPIType("Unsupported API type %s" % self.api_type)
raise error.InvalidAPIType(f"Unsupported API type {self.api_type}")
Comment on lines -68 to +75
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function APIResource.instance_url refactored with the following changes:


# The `method_` and `url_` arguments are suffixed with an underscore to
# avoid conflicting with actual request parameters in `params`.
Expand Down
4 changes: 2 additions & 2 deletions openai/api_resources/abstract/createable_api_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ def create(

if typed_api_type in (ApiType.AZURE, ApiType.AZURE_AD):
base = cls.class_url()
url = "/%s%s?api-version=%s" % (cls.azure_api_prefix, base, api_version)
url = f"/{cls.azure_api_prefix}{base}?api-version={api_version}"
elif typed_api_type == ApiType.OPEN_AI:
url = cls.class_url()
else:
raise error.InvalidAPIType("Unsupported API type %s" % api_type)
raise error.InvalidAPIType(f"Unsupported API type {api_type}")
Comment on lines -33 to +37
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function CreateableAPIResource.create refactored with the following changes:


response, _, api_key = requestor.request(
"post", url, params, request_id=request_id
Expand Down
11 changes: 3 additions & 8 deletions openai/api_resources/abstract/deletable_api_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,11 @@ def delete(cls, sid, api_type=None, api_version=None, **params):
api_type, api_version
)
if typed_api_type in (ApiType.AZURE, ApiType.AZURE_AD):
url = "/%s%s/%s?api-version=%s" % (
cls.azure_api_prefix,
base,
extn,
api_version,
)
url = f"/{cls.azure_api_prefix}{base}/{extn}?api-version={api_version}"
elif typed_api_type == ApiType.OPEN_AI:
url = "%s/%s" % (base, extn)
url = f"{base}/{extn}"
else:
raise error.InvalidAPIType("Unsupported API type %s" % api_type)
raise error.InvalidAPIType(f"Unsupported API type {api_type}")
Comment on lines -21 to +25
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DeletableAPIResource.delete refactored with the following changes:


return cls._static_request(
"delete", url, api_type=api_type, api_version=api_version, **params
Expand Down
46 changes: 15 additions & 31 deletions openai/api_resources/abstract/engine_api_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,23 +42,17 @@ def class_url(
"You must provide the deployment name in the 'engine' parameter to access the Azure OpenAI service"
)
extn = quote_plus(engine)
return "/%s/%s/%s/%s?api-version=%s" % (
cls.azure_api_prefix,
cls.azure_deployments_prefix,
extn,
base,
api_version,
)
return f"/{cls.azure_api_prefix}/{cls.azure_deployments_prefix}/{extn}/{base}?api-version={api_version}"

elif typed_api_type == ApiType.OPEN_AI:
if engine is None:
return "/%s" % (base)
return f"/{base}"

extn = quote_plus(engine)
return "/engines/%s/%s" % (extn, base)
return f"/engines/{extn}/{base}"

else:
raise error.InvalidAPIType("Unsupported API type %s" % api_type)
raise error.InvalidAPIType(f"Unsupported API type {api_type}")
Comment on lines -45 to +55
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function EngineAPIResource.class_url refactored with the following changes:


@classmethod
def create(
Expand All @@ -73,7 +67,7 @@ def create(
):
deployment_id = params.pop("deployment_id", None)
engine = params.pop("engine", deployment_id)
model = params.get("model", None)
model = params.get("model")
Comment on lines -76 to +70
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function EngineAPIResource.create refactored with the following changes:

timeout = params.pop("timeout", None)
stream = params.get("stream", False)
headers = params.pop("headers", None)
Expand All @@ -82,17 +76,14 @@ def create(
if typed_api_type in (util.ApiType.AZURE, util.ApiType.AZURE_AD):
if deployment_id is None and engine is None:
raise error.InvalidRequestError(
"Must provide an 'engine' or 'deployment_id' parameter to create a %s"
% cls,
"engine",
)
else:
if model is None and engine is None:
raise error.InvalidRequestError(
"Must provide an 'engine' or 'model' parameter to create a %s"
% cls,
f"Must provide an 'engine' or 'deployment_id' parameter to create a {cls}",
"engine",
)
elif model is None and engine is None:
raise error.InvalidRequestError(
f"Must provide an 'engine' or 'model' parameter to create a {cls}",
"engine",
)

if timeout is None:
# No special timeout handling
Expand Down Expand Up @@ -170,27 +161,20 @@ def instance_url(self):
"An API version is required for the Azure API type."
)
base = self.OBJECT_NAME.replace(".", "/")
url = "/%s/%s/%s/%s/%s?api-version=%s" % (
self.azure_api_prefix,
self.azure_deployments_prefix,
self.engine,
base,
extn,
api_version,
)
url = f"/{self.azure_api_prefix}/{self.azure_deployments_prefix}/{self.engine}/{base}/{extn}?api-version={api_version}"
params_connector = "&"

elif self.typed_api_type == ApiType.OPEN_AI:
base = self.class_url(self.engine, self.api_type, self.api_version)
url = "%s/%s" % (base, extn)
url = f"{base}/{extn}"

else:
raise error.InvalidAPIType("Unsupported API type %s" % self.api_type)
raise error.InvalidAPIType(f"Unsupported API type {self.api_type}")

timeout = self.get("timeout")
if timeout is not None:
timeout = quote_plus(str(timeout))
url += params_connector + "timeout={}".format(timeout)
url += f"{params_connector}timeout={timeout}"
Comment on lines -173 to +177
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function EngineAPIResource.instance_url refactored with the following changes:

return url

def wait(self, timeout=None):
Expand Down
4 changes: 2 additions & 2 deletions openai/api_resources/abstract/listable_api_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ def list(

if typed_api_type in (ApiType.AZURE, ApiType.AZURE_AD):
base = cls.class_url()
url = "/%s%s?api-version=%s" % (cls.azure_api_prefix, base, api_version)
url = f"/{cls.azure_api_prefix}{base}?api-version={api_version}"
elif typed_api_type == ApiType.OPEN_AI:
url = cls.class_url()
else:
raise error.InvalidAPIType("Unsupported API type %s" % api_type)
raise error.InvalidAPIType(f"Unsupported API type {api_type}")
Comment on lines -36 to +40
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function ListableAPIResource.list refactored with the following changes:


response, _, api_key = requestor.request(
"get", url, params, request_id=request_id
Expand Down
22 changes: 11 additions & 11 deletions openai/api_resources/abstract/nested_resource_class_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@ def nested_resource_class_methods(
resource, path=None, operations=None, resource_plural=None
):
if resource_plural is None:
resource_plural = "%ss" % resource
resource_plural = f"{resource}s"
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function nested_resource_class_methods refactored with the following changes:

if path is None:
path = resource_plural
if operations is None:
raise ValueError("operations list required")

def wrapper(cls):
def nested_resource_url(cls, id, nested_id=None):
url = "%s/%s/%s" % (cls.class_url(), quote_plus(id), quote_plus(path))
url = f"{cls.class_url()}/{quote_plus(id)}/{quote_plus(path)}"
if nested_id is not None:
url += "/%s" % quote_plus(nested_id)
url += f"/{quote_plus(nested_id)}"
return url

resource_url_method = "%ss_url" % resource
resource_url_method = f"{resource}s_url"
setattr(cls, resource_url_method, classmethod(nested_resource_url))

def nested_resource_request(
Expand All @@ -43,7 +43,7 @@ def nested_resource_request(
response, api_key, api_version, organization
)

resource_request_method = "%ss_request" % resource
resource_request_method = f"{resource}s_request"
setattr(cls, resource_request_method, classmethod(nested_resource_request))

for operation in operations:
Expand All @@ -53,7 +53,7 @@ def create_nested_resource(cls, id, **params):
url = getattr(cls, resource_url_method)(id)
return getattr(cls, resource_request_method)("post", url, **params)

create_method = "create_%s" % resource
create_method = f"create_{resource}"
setattr(cls, create_method, classmethod(create_nested_resource))

elif operation == "retrieve":
Expand All @@ -62,7 +62,7 @@ def retrieve_nested_resource(cls, id, nested_id, **params):
url = getattr(cls, resource_url_method)(id, nested_id)
return getattr(cls, resource_request_method)("get", url, **params)

retrieve_method = "retrieve_%s" % resource
retrieve_method = f"retrieve_{resource}"
setattr(cls, retrieve_method, classmethod(retrieve_nested_resource))

elif operation == "update":
Expand All @@ -71,7 +71,7 @@ def modify_nested_resource(cls, id, nested_id, **params):
url = getattr(cls, resource_url_method)(id, nested_id)
return getattr(cls, resource_request_method)("post", url, **params)

modify_method = "modify_%s" % resource
modify_method = f"modify_{resource}"
setattr(cls, modify_method, classmethod(modify_nested_resource))

elif operation == "delete":
Expand All @@ -82,7 +82,7 @@ def delete_nested_resource(cls, id, nested_id, **params):
"delete", url, **params
)

delete_method = "delete_%s" % resource
delete_method = f"delete_{resource}"
setattr(cls, delete_method, classmethod(delete_nested_resource))

elif operation == "list":
Expand All @@ -91,11 +91,11 @@ def list_nested_resources(cls, id, **params):
url = getattr(cls, resource_url_method)(id)
return getattr(cls, resource_request_method)("get", url, **params)

list_method = "list_%s" % resource_plural
list_method = f"list_{resource_plural}"
setattr(cls, list_method, classmethod(list_nested_resources))

else:
raise ValueError("Unknown operation: %s" % operation)
raise ValueError(f"Unknown operation: {operation}")

return cls

Expand Down
2 changes: 1 addition & 1 deletion openai/api_resources/abstract/updateable_api_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
class UpdateableAPIResource(APIResource):
@classmethod
def modify(cls, sid, **params):
url = "%s/%s" % (cls.class_url(), quote_plus(sid))
url = f"{cls.class_url()}/{quote_plus(sid)}"
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function UpdateableAPIResource.modify refactored with the following changes:

return cls._static_request("post", url, **params)
2 changes: 1 addition & 1 deletion openai/api_resources/answer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

class Answer(OpenAIObject):
@classmethod
def get_url(self):
def get_url(cls):
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Answer.get_url refactored with the following changes:

return "/answers"

@classmethod
Expand Down
2 changes: 1 addition & 1 deletion openai/api_resources/classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

class Classification(OpenAIObject):
@classmethod
def get_url(self):
def get_url(cls):
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Classification.get_url refactored with the following changes:

return "/classifications"

@classmethod
Expand Down
2 changes: 1 addition & 1 deletion openai/api_resources/customer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

class Customer(OpenAIObject):
@classmethod
def get_url(self, customer, endpoint):
def get_url(cls, customer, endpoint):
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Customer.get_url refactored with the following changes:

return f"/customer/{customer}/{endpoint}"

@classmethod
Expand Down
2 changes: 1 addition & 1 deletion openai/api_resources/deployment.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def create(cls, *args, **kwargs):
param="model",
)

scale_settings = kwargs.get("scale_settings", None)
scale_settings = kwargs.get("scale_settings")
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Deployment.create refactored with the following changes:

if scale_settings is None:
raise InvalidRequestError(
"Must provide a 'scale_settings' parameter to create a Deployment.",
Expand Down
2 changes: 1 addition & 1 deletion openai/api_resources/embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def create(cls, *args, **kwargs):
start = time.time()
timeout = kwargs.pop("timeout", None)

user_provided_encoding_format = kwargs.get("encoding_format", None)
user_provided_encoding_format = kwargs.get("encoding_format")
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Embedding.create refactored with the following changes:


# If encoding format was not explicitly specified, we opaquely use base64 for performance
if not user_provided_encoding_format:
Expand Down
Loading