Skip to content

Commit d928a52

Browse files
committed
chore(internal): minor updates
1 parent cda08c6 commit d928a52

23 files changed

+184
-92
lines changed

README.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ from openai import OpenAI
2525

2626
client = OpenAI(
2727
# defaults to os.environ.get("OPENAI_API_KEY")
28-
api_key="my api key",
28+
api_key="My API Key",
2929
)
3030

3131
completion = client.chat.completions.create(
@@ -40,8 +40,10 @@ completion = client.chat.completions.create(
4040
print(completion.choices)
4141
```
4242

43-
While you can provide an `api_key` keyword argument, we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/)
44-
and adding `OPENAI_API_KEY="my api key"` to your `.env` file so that your API Key is not stored in source control.
43+
While you can provide an `api_key` keyword argument,
44+
we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/)
45+
to add `OPENAI_API_KEY="My API Key"` to your `.env` file
46+
so that your API Key is not stored in source control.
4547

4648
## Async usage
4749

@@ -52,7 +54,7 @@ from openai import AsyncOpenAI
5254

5355
client = AsyncOpenAI(
5456
# defaults to os.environ.get("OPENAI_API_KEY")
55-
api_key="my api key",
57+
api_key="My API Key",
5658
)
5759

5860

bin/check-test-server

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,13 +10,13 @@ function prism_is_running() {
1010
}
1111

1212
function is_overriding_api_base_url() {
13-
[ -n "$API_BASE_URL" ]
13+
[ -n "$TEST_API_BASE_URL" ]
1414
}
1515

1616
if is_overriding_api_base_url ; then
1717
# If someone is running the tests against the live API, we can trust they know
1818
# what they're doing and exit early.
19-
echo -e "${GREEN}✔ Running tests against ${API_BASE_URL}${NC}"
19+
echo -e "${GREEN}✔ Running tests against ${TEST_API_BASE_URL}${NC}"
2020

2121
exit 0
2222
elif prism_is_running ; then

examples/azure.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import os
2-
from openai import OpenAI
32

3+
from openai import OpenAI
44

55
# The name of your Azure OpenAI Resource.
66
# https://learn.microsoft.com/en-us/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource

examples/demo.py

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,30 +6,18 @@
66
client = OpenAI()
77

88
# Non-streaming:
9-
print('----- standard request -----')
10-
completion = client.chat.completions.create(
11-
model="gpt-4",
12-
messages=[
13-
{
14-
"role": "user",
15-
"content": "Say this is a test",
16-
},
17-
],
9+
completion = client.completions.create(
10+
model="text-davinci-003",
11+
prompt="Say this is a test",
1812
)
19-
print(completion.choices[0].message.content)
13+
print(completion.choices[0].text)
2014

2115
# Streaming:
22-
print('----- streaming request -----')
23-
stream = client.chat.completions.create(
24-
model="gpt-4",
25-
messages=[
26-
{
27-
"role": "user",
28-
"content": "How do I output all files in a directory using Python?",
29-
},
30-
],
16+
stream = client.completions.create(
17+
model="text-davinci-003",
18+
prompt="Say this is a test",
3119
stream=True,
3220
)
3321
for completion in stream:
34-
print(completion.choices[0].delta.content, end="")
22+
print(completion.choices[0].text, end="")
3523
print()

src/openai/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@
9595

9696
api_key: str | None = _os.environ.get("OPENAI_API_KEY")
9797

98-
organization: str | None = _os.environ.get("OPENAI_ORG_ID") or None
98+
organization: str | None = _os.environ.get("OPENAI_ORG_ID")
9999

100100
base_url: str | None = None
101101

src/openai/_base_client.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import json
44
import time
55
import uuid
6+
import email
67
import inspect
78
import logging
89
import platform
@@ -655,10 +656,22 @@ def _calculate_retry_timeout(
655656
try:
656657
# About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
657658
#
658-
# TODO: we may want to handle the case where the header is using the http-date syntax: "Retry-After:
659659
# <http-date>". See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax for
660660
# details.
661-
retry_after = -1 if response_headers is None else int(response_headers.get("retry-after"))
661+
if response_headers is not None:
662+
retry_header = response_headers.get("retry-after")
663+
try:
664+
retry_after = int(retry_header)
665+
except Exception:
666+
retry_date_tuple = email.utils.parsedate_tz(retry_header)
667+
if retry_date_tuple is None:
668+
retry_after = -1
669+
else:
670+
retry_date = email.utils.mktime_tz(retry_date_tuple)
671+
retry_after = int(retry_date - time.time())
672+
else:
673+
retry_after = -1
674+
662675
except Exception:
663676
retry_after = -1
664677

@@ -803,7 +816,10 @@ def close(self) -> None:
803816
804817
The client will *not* be usable after this.
805818
"""
806-
self._client.close()
819+
# If an error is thrown while constructing a client, self._client
820+
# may not be present
821+
if hasattr(self, "_client"):
822+
self._client.close()
807823

808824
def __enter__(self: _T) -> _T:
809825
return self

src/openai/_client.py

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,9 @@ class OpenAI(SyncAPIClient):
5959
def __init__(
6060
self,
6161
*,
62+
api_key: str | None = None,
6263
organization: str | None = None,
6364
base_url: Optional[str] = None,
64-
api_key: Optional[str] = None,
6565
timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN,
6666
max_retries: int = DEFAULT_MAX_RETRIES,
6767
default_headers: Mapping[str, str] | None = None,
@@ -84,15 +84,17 @@ def __init__(
8484
- `api_key` from `OPENAI_API_KEY`
8585
- `organization` from `OPENAI_ORG_ID`
8686
"""
87-
api_key = api_key or os.environ.get("OPENAI_API_KEY", None)
88-
if not api_key:
87+
if api_key is None:
88+
api_key = os.environ.get("OPENAI_API_KEY")
89+
if api_key is None:
8990
raise OpenAIError(
9091
"The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable"
9192
)
9293
self.api_key = api_key
9394

94-
organization_envvar = os.environ.get("OPENAI_ORG_ID", None)
95-
self.organization = organization or organization_envvar or None
95+
if organization is None:
96+
organization = os.environ.get("OPENAI_ORG_ID") or None
97+
self.organization = organization
9698

9799
if base_url is None:
98100
base_url = f"https://api.openai.com/v1"
@@ -142,8 +144,8 @@ def default_headers(self) -> dict[str, str | Omit]:
142144
def copy(
143145
self,
144146
*,
145-
organization: str | None = None,
146147
api_key: str | None = None,
148+
organization: str | None = None,
147149
base_url: str | None = None,
148150
timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
149151
http_client: httpx.Client | None = None,
@@ -179,9 +181,9 @@ def copy(
179181

180182
http_client = http_client or self._client
181183
return self.__class__(
184+
api_key=api_key or self.api_key,
182185
organization=organization or self.organization,
183186
base_url=base_url or str(self.base_url),
184-
api_key=api_key or self.api_key,
185187
timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
186188
http_client=http_client,
187189
max_retries=max_retries if is_given(max_retries) else self.max_retries,
@@ -256,9 +258,9 @@ class AsyncOpenAI(AsyncAPIClient):
256258
def __init__(
257259
self,
258260
*,
261+
api_key: str | None = None,
259262
organization: str | None = None,
260263
base_url: Optional[str] = None,
261-
api_key: Optional[str] = None,
262264
timeout: Union[float, Timeout, None, NotGiven] = NOT_GIVEN,
263265
max_retries: int = DEFAULT_MAX_RETRIES,
264266
default_headers: Mapping[str, str] | None = None,
@@ -281,15 +283,17 @@ def __init__(
281283
- `api_key` from `OPENAI_API_KEY`
282284
- `organization` from `OPENAI_ORG_ID`
283285
"""
284-
api_key = api_key or os.environ.get("OPENAI_API_KEY", None)
285-
if not api_key:
286+
if api_key is None:
287+
api_key = os.environ.get("OPENAI_API_KEY")
288+
if api_key is None:
286289
raise OpenAIError(
287290
"The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable"
288291
)
289292
self.api_key = api_key
290293

291-
organization_envvar = os.environ.get("OPENAI_ORG_ID", None)
292-
self.organization = organization or organization_envvar or None
294+
if organization is None:
295+
organization = os.environ.get("OPENAI_ORG_ID") or None
296+
self.organization = organization
293297

294298
if base_url is None:
295299
base_url = f"https://api.openai.com/v1"
@@ -339,8 +343,8 @@ def default_headers(self) -> dict[str, str | Omit]:
339343
def copy(
340344
self,
341345
*,
342-
organization: str | None = None,
343346
api_key: str | None = None,
347+
organization: str | None = None,
344348
base_url: str | None = None,
345349
timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
346350
http_client: httpx.AsyncClient | None = None,
@@ -376,9 +380,9 @@ def copy(
376380

377381
http_client = http_client or self._client
378382
return self.__class__(
383+
api_key=api_key or self.api_key,
379384
organization=organization or self.organization,
380385
base_url=base_url or str(self.base_url),
381-
api_key=api_key or self.api_key,
382386
timeout=self.timeout if isinstance(timeout, NotGiven) else timeout,
383387
http_client=http_client,
384388
max_retries=max_retries if is_given(max_retries) else self.max_retries,

src/openai/_utils/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121
from ._utils import extract_type_arg as extract_type_arg
2222
from ._utils import is_required_type as is_required_type
2323
from ._utils import is_annotated_type as is_annotated_type
24+
from ._utils import maybe_coerce_float as maybe_coerce_float
25+
from ._utils import maybe_coerce_boolean as maybe_coerce_boolean
26+
from ._utils import maybe_coerce_integer as maybe_coerce_integer
2427
from ._utils import strip_annotated_type as strip_annotated_type
2528
from ._transform import PropertyInfo as PropertyInfo
2629
from ._transform import transform as transform

src/openai/_utils/_utils.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,6 +309,24 @@ def coerce_boolean(val: str) -> bool:
309309
return val == "true" or val == "1" or val == "on"
310310

311311

312+
def maybe_coerce_integer(val: str | None) -> int | None:
313+
if val is None:
314+
return None
315+
return coerce_integer(val)
316+
317+
318+
def maybe_coerce_float(val: str | None) -> float | None:
319+
if val is None:
320+
return None
321+
return coerce_float(val)
322+
323+
324+
def maybe_coerce_boolean(val: str | None) -> bool | None:
325+
if val is None:
326+
return None
327+
return coerce_boolean(val)
328+
329+
312330
def removeprefix(string: str, prefix: str) -> str:
313331
"""Remove a prefix from a string.
314332

tests/api_resources/audio/test_transcriptions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@
1010
from tests.utils import assert_matches_type
1111
from openai.types.audio import Transcription
1212

13-
base_url = os.environ.get("API_BASE_URL", "http://127.0.0.1:4010")
14-
api_key = os.environ.get("API_KEY", "something1234")
13+
base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
14+
api_key = "My API Key"
1515

1616

1717
class TestTranscriptions:

0 commit comments

Comments
 (0)